[英]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.