简体   繁体   English

Python 如何为列表中的每个项目创建集合?

[英]Python How can I create sets for every item in my list?

How can I create sets for every item in my list?如何为列表中的每个项目创建集合?

This is my list:这是我的清单:

listofstrings = ['sdfasdf', 'sdfaserth', 'wegoiog']

I want it to create sets like this:我希望它创建这样的集合:

set1 = set(), set2=set(), set3=set()

You can create a list of them like this您可以像这样创建它们的列表

sets = []
listofstrings=['sdfasdf', 'sdfaserth', 'wegoiog']
for string in listofstrings:
    sets.append(set())

I would use a dictionary to do it(so you can access each set matching the corresponding string).我会使用字典来做这件事(这样你就可以访问与相应字符串匹配的每个集合)。

name_to_set = {}
listofstring = ['sdfasdf', 'sdfaserth', 'wegoiog']
name_to_set = {name: set() for name in listofstring}

so later you can use it as follows:所以稍后您可以按如下方式使用它:

name_to_set['sdfasdf'].add('x')

You can create as following:您可以创建如下:

for index, word in enumerate(listofstrings):
    exec("set%d = %s" % (index + 1, set()))
listofstrings=['sdfasdf', 'sdfaserth', 'wegoiog']
l = [set() for se in listofstrings]

As I mentioned, this question is unclear and probably a case of the XY problem .正如我所提到的,这个问题不清楚,可能是XY 问题的一个案例。 I feel the need to share a solution because so many of the current ones are bizarre at best.我觉得有必要分享一个解决方案,因为目前的许多解决方案充其量只是奇怪的。

list_of_strs = ['sdfasdf', 'sdfaserth', 'wegoiog']

sets_list = [set() for _ in list_of_strs]

Notice I changed the variable names.请注意,我更改了变量名称。 In Python, variable names should generally follow the lower_case_with_underscores style.在 Python 中,变量名通常应遵循lower_case_with_underscores样式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM