简体   繁体   中英

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.

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_exists = [ any(subset) for subset in varList ]

you also check if all the elements are True using the all keyword

尝试

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 :

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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