列表中的第一个值等于另一个列表中的第一个值。 python2.7

时间:2017-01-24 21:37:42

标签: python-2.7 list arraylist sublist

所以想象我有一个子列表

exList = [
    ['green', 'apple', 'NO'],
    ['red','apple','nO'],
    ['red','watermellon','no'],
    ['yellow','honeymellon','yes']
]

所以我想检查列表中的第一个值是否等于另一个列表中的第一个值。

所以exlist是一个子列表,它有4个不同的列表。所以我想检查第一个列表中的第一个值,并检查它是否等于另一个列表中的任何其他值。所以Green是第一个值,绿色没有在另一个列表中使用,所以它应该返回False。但如果在其他列表中使用了绿色,它应该返回True。

for i in exList:
    if i+1[1] == i-[1]:
        print True

我该怎么做?

1 个答案:

答案 0 :(得分:0)

因此,如果我理解您的请求,您想要检查exList中第一个列表的第一个值是否存在于每个剩余列表中?如果是这样,您可以使用列表推导如下:

check = [True if (exList[0][0] in subList) else False for subList in exList[1:]]

如果你不理解列表理解,你可以在循环中执行此操作:

check = []
checkItem = exList[0][0] #Pulls the value for the first item in the first list of exList
for i in range(1,len(exList)): #Starts at 1 to skip the first list in exList
  check.append(checkItem in exList[i])
print check

如果你需要遍历第一个列表中的每个项目来检查:

for eachListItem in exList[0]:
  print "Search Text: %s" % (eachListItem)
  curCheck = [True if (eachListItem in subList) else False for subList in exList[1:]]
  print "Search Results: %s" % (True in curCheck)

注意:这些都不会占用字符串中的空格或不匹配的情况(I.E. NO和No是两个不同的值并返回false。类似地“No”和“No”不同)