解压列表为多个变量

huangapple go评论63阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年3月3日 23:17:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75628857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定