亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

對每列中的項目進行獨特組合

對每列中的項目進行獨特組合

守著星空守著你 2023-06-20 14:39:29
我有一個看起來像這樣的 CSV 文件:    Person 1  Person 2  Person 3   Person 4a      Apple     Apple       Yam       Beerb     Orange    Orange   Doritos     Cheesec  Pineapple  Nintendo     Apple      Sushid      Pizza    Cheese    Orange  Pineapplee    Doritos     Fanta     Pizza     Orangef       Coke    Fajita      Cake       Cokeg Strawberry     Juice      Beer        Teah Blackberry                           Yami      Sushi每列代表每個人,每一行是每個對應(行)人喜歡的項目。我正在嘗試提出一種算法,可以給我一個獨特組合的列表,每個項目只使用一次,同時給一個人一個他想要的項目。就像是:1)    Person 1  Person 2  Person 3   Person 4       Apple    Orange       Yam       Beer2)    Person 1  Person 2  Person 3   Person 4       Apple    Orange       Yam     Cheese.. 很快。請有人指導我如何解決這個問題?我是python的新手。
查看完整描述

4 回答

?
蠱毒傳說

TA貢獻1895條經驗 獲得超3個贊

沒有圖書館:


pools = ['Apple', 'Orange', ...], ['Apple', 'Orange', ...], [...], [...]]

result = [[]]

for pool in pools:

    result = [x+[y] for x in result for y in pool if y not in x]


print(result)


查看完整回答
反對 回復 2023-06-20
?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

pools = [['Apple', 'Orange','Pineapple'], ['Apple', 'Orange','pizza'],['Apple', 

         'Orange','pizza','beer']]


results = []

for pool in pools:  

    results.append([item for item in pool if item not in results][0])


Output: ['Apple', 'Orange', 'pizza']


查看完整回答
反對 回復 2023-06-20
?
慕娘9325324

TA貢獻1783條經驗 獲得超4個贊

我會使用 itertools.product() 來生成組合,然后使用 set() 選擇有效組合(沒有重復項)。


是這樣的:


from itertools import product


person_1 = ['Apple', 'Orange', 'Pineapple', ...]

person_2 = ['Apple', 'Orange', 'Nintendo', ...]

person_3 = ['Yam', 'Doritos', 'Apple', ...]

person_4 = ['Beer', 'Cheese', 'Sushi', ...]



for p in product(person_1, person_2, person_3, person_4):

    if len(p) == len(set(p)):

        print(p)


查看完整回答
反對 回復 2023-06-20
?
大話西游666

TA貢獻1817條經驗 獲得超14個贊

這是使用熊貓的另一種方法:


import pandas as pd



d= {"Person 1" : ['Apple', 'Orange', 'Pineapple', ...],"Person 2" : ['Apple', 'Orange', 'Nintendo', ...],"Person 3" : ['Yam', 'Doritos', 'Apple', ...],"Person 4" : ['Beer', 'Cheese', 'Sushi', ...]}


df = pd.DataFrame(data=d)

df=df.drop_duplicates()

df=df.dropna(axis=0)


print(df)


查看完整回答
反對 回復 2023-06-20
  • 4 回答
  • 0 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號