If I have a tuple such as (1,2,3,4)
and I want to assign 1 and 3 to variables a and b I could obviously say
如果我有一个元组,如(1,2,3,4),我想将1和3分配给变量a和b,我可以明显地说
myTuple = (1,2,3)
a = my_tuple[0]
b = myTuple[2]
Or something like
或类似的东西
(a,_,b,_) = myTuple
Is there a way I could unpack the values, but ignore one or more of them of them?
有没有办法可以解压缩值,但忽略它们中的一个或多个?
2 个解决方案
#1
11
Your solution is fine in my opinion. If you really have a problem with assigning _ then you could define a list of indexes and do:
在我看来,你的解决方案很好。如果您确实在分配_时遇到问题,那么您可以定义索引列表并执行:
a = (1, 2, 3, 4, 5)
idxs = [0, 3, 4]
a1, b1, c1 = (a[i] for i in idxs)
#2
39
I personally would write:
我个人会写:
a, _, b = myTuple
This is a pretty common idiom, so it's widely understood. I find the syntax crystal clear.
这是一个非常常见的习语,因此它被广泛理解。我发现语法清晰。
#1
11
Your solution is fine in my opinion. If you really have a problem with assigning _ then you could define a list of indexes and do:
在我看来,你的解决方案很好。如果您确实在分配_时遇到问题,那么您可以定义索引列表并执行:
a = (1, 2, 3, 4, 5)
idxs = [0, 3, 4]
a1, b1, c1 = (a[i] for i in idxs)
#2
39
I personally would write:
我个人会写:
a, _, b = myTuple
This is a pretty common idiom, so it's widely understood. I find the syntax crystal clear.
这是一个非常常见的习语,因此它被广泛理解。我发现语法清晰。