[英]Python How can I create sets for every item in my list?
如何為列表中的每個項目創建集合?
這是我的清單:
listofstrings = ['sdfasdf', 'sdfaserth', 'wegoiog']
我希望它創建這樣的集合:
set1 = set(), set2=set(), set3=set()
您可以像這樣創建它們的列表
sets = []
listofstrings=['sdfasdf', 'sdfaserth', 'wegoiog']
for string in listofstrings:
sets.append(set())
我會使用字典來做這件事(這樣你就可以訪問與相應字符串匹配的每個集合)。
name_to_set = {}
listofstring = ['sdfasdf', 'sdfaserth', 'wegoiog']
name_to_set = {name: set() for name in listofstring}
所以稍后您可以按如下方式使用它:
name_to_set['sdfasdf'].add('x')
您可以創建如下:
for index, word in enumerate(listofstrings):
exec("set%d = %s" % (index + 1, set()))
listofstrings=['sdfasdf', 'sdfaserth', 'wegoiog']
l = [set() for se in listofstrings]
正如我所提到的,這個問題不清楚,可能是XY 問題的一個案例。 我覺得有必要分享一個解決方案,因為目前的許多解決方案充其量只是奇怪的。
list_of_strs = ['sdfasdf', 'sdfaserth', 'wegoiog']
sets_list = [set() for _ in list_of_strs]
請注意,我更改了變量名稱。 在 Python 中,變量名通常應遵循lower_case_with_underscores
樣式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.