[英]How to identify a value inside of a tuple in a python list?
我正在尋找一些pythonic解決方案來檢查列表中的元組中是否存在True或False。
我確實是這樣的:
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)]
如何更好地做到這一點?
嘗試
result = True in varList[0]
如果您還想返回元組的索引以及元組內發生的索引,可以嘗試:
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))
結果將是:
[(True, 0, 0), (True, 1, 0)]
哪里:
第一個參數表示找到了值。
第二個參數指定列表中元組的索引。
第三個參數指定在該元組中找到的值的索引。
這是建議使用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))
結果將是:
[(True, 0, 0), (True, 1, 0)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.