忽略 python 元组的一部分 [英] Ignore part of a python tuple

查看:44
本文介绍了忽略 python 元组的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个元组,例如 (1,2,3,4) 并且我想将 1 和 3 分配给变量 a 和 b,我显然可以说

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

myTuple = (1,2,3)
a = my_tuple[0]
b = myTuple[2]

或者类似的东西

(a,_,b,_) = myTuple

有没有一种方法可以解压缩这些值,但忽略其中的一个或多个?

Is there a way I could unpack the values, but ignore one or more of them of them?

推荐答案

我认为您的解决方案很好.如果您确实在分配 _ 时遇到问题,那么您可以定义一个索引列表并执行:

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)

这篇关于忽略 python 元组的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆