[英]Python - Create a list of sets or set of sets?
對於我正在審核的課程,需要幫助完成家庭作業。 練習是關聯規則挖掘,我非常堅持組織數據的其中一個步驟。
我有一串由換行符分隔的數據(每行代表客戶購買的商品):
rawText =
"""fruit, bread, butter, soup
fruit, yogurt, coffee
whole milk, cream cheese, meat, vegetables"""
如何將這些數據放入一個看起來像這樣的集合(這是一個集合列表?):
[{‘fruit’, ‘bread’, ‘butter’, soup’},
{‘fruit’, ‘yogurt’, ‘coffee’},
{'whole milk', 'cream cheese', 'meat', 'vegetables'}
]
我試圖在行尾打破字符串:
names_list = [y for y in (x.strip() for x in rawText.splitlines()) if y]
my_set = set()
for i in names_list:
my_set.add(i)
這顯然不起作用。 也許我會以錯誤的方式解決這個問題?
要獲取每個集合的集合列表,其中包含來自給定行的逗號分隔的單詞:
names_list = [set(line.strip().split(', ')) for line in raw_text.splitlines()]
你很近但有兩個問題:
鑒於此,這應該可以解決您的問題
names_list = [set(line.strip().split(',')) for line in raw_text.splitlines()]
作為替代方案,您可以使用csv
模塊來處理行拆分,空格和分隔符:
import csv
from io import StringIO
x = StringIO("""fruit, bread, butter, soup
fruit, yogurt, coffee
whole milk, cream cheese, meat, vegetables""")
with x as fin:
reader = csv.reader(fin, skipinitialspace=True)
res = list(map(set, reader))
結果
print(res)
[{'bread', 'butter', 'fruit', 'soup'},
{'coffee', 'fruit', 'yogurt'},
{'cream cheese', 'meat', 'vegetables', 'whole milk'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.