简体   繁体   English

如何在python列表中的元组中识别值?

[英]How to identify a value inside of a tuple in a python list?

I'm looking for some pythonic solution to check if there are True or False in a tuple inside of a list. 我正在寻找一些pythonic解决方案来检查列表中的元组中是否存在True或False。

I did like this: 我确实是这样的:

varList = [(True,)]
temp = varList.pop(0)
result = temp[temp.index(True,)]
print result

#############
# If there are more complex result 
varList = [(True, False, False), (True, False)]    

How to do this in a better way? 如何更好地做到这一点?

if your intention is to check if the value True exists in a tuple or tuples you could use any keyword like the following : 如果您打算检查一个或多个元组中是否存在True值,则可以使用以下任何关键字:

true_exists = [ any(subset) for subset in varList ]

you also check if all the elements are True using the all keyword 您还使用all关键字检查所有元素是否为True

尝试

result = True in varList[0]

In case you want also want to return the index of the tuple as well as the index of the occurence within than tuple, you can try: 如果您还想返回元组的索引以及元组内发生的索引,可以尝试:

  def isValueInList(varList, value):
       return [(varList[lst][i],lst,i) for lst in range(len(varList)) for i in range(len(varList[lst])) if varList[lst][i] == value]

 print(isValueInList(varList, True))

The result will be: 结果将是:

[(True, 0, 0), (True, 1, 0)]

where: 哪里:

First argument means that value was found. 第一个参数表示找到了值。

Second argument specifies the index of the tuple within the list. 第二个参数指定列表中元组的索引。

Third argument specifies the index of the value that was found within that tuple. 第三个参数指定在该元组中找到的值的索引。

Here is the suggested edit using enumerate : 这是建议使用enumerate编辑:

def isValueInList(varList, value):

   return [(val,innerInd, tupInd) for tupInd, tup in enumerate(varList) for innerInd, val in enumerate(tup) if val==value]

print(isValueInList(varList, True))

The result will be: 结果将是:

[(True, 0, 0), (True, 1, 0)]

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

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