英文:
Unpacking a list into multiple variables
问题
有没有一种方法可以将一个列表中的多个列表解压到多个变量中?
scores = [['S', 'R'], ['A', 'B'], ['X', 'Y'], ['P', 'Q']]
转换为:
a = ['S', 'R'], b = ['A', 'B'], c = ['X', 'Y'], d = ['P', 'Q']
似乎这应该是相当简单的事情,但是我无法找到一种解决方案,它不涉及将所有单独的元素提取到一个大列表中,这不是我想要的。我想保留这4个单独的对象,只是不想将它们存储在一个列表或字典中。
寻找一个通用解决方案,可以适用于列表中的列表数量/变量数量发生变化的情况。
英文:
Is there a way to unpack a list of lists, but into multiple variables?
scores = [['S', 'R'], ['A', 'B'], ['X', 'Y'], ['P', 'Q']]
Into:
a = ['S', 'R'], b = ['A', 'B'], c = ['X', 'Y'], d = ['P', 'Q']
Seems like something that should be quite simple and yet I'm unable to find a solution that doesn't involve extracting all the individual elements into one big list, which is not what I want to do. I want to retain the 4 individual objects, just not stored inside a list or dictionary.
Looking for a general solution that might apply if the number of lists within the list / number of variables change.
答案1
得分: 3
生成变量编程方式不是一个好主意,最好使用字典:
from string import ascii_lowercase
scores = [['S', 'R'], ['A', 'B'], ['X', 'Y'], ['P', 'Q']]
dic = dict(zip(ascii_lowercase, scores))
注意:依我个人看法,最好保留原始列表。
输出:
{'a': ['S', 'R'], 'b': ['A', 'B'], 'c': ['X', 'Y'], 'd': ['P', 'Q']}
或者,如果你知道有多少个列表,你可以解包它们:
a, b, c, d = scores
英文:
Generating variable programmatically is not a good idea, rather use a dictionary:
from string import ascii_lowercase
scores = [['S', 'R'], ['A', 'B'], ['X', 'Y'], ['P', 'Q']]
dic = dict(zip(ascii_lowercase, scores))
NB. IMO it's still better to keep the original list.
Output:
{'a': ['S', 'R'], 'b': ['A', 'B'], 'c': ['X', 'Y'], 'd': ['P', 'Q']}
Or, if you have a known number of lists, unpack them:
a, b, c, d = scores
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论