[英]How to compare string vs. list of lists in Python/Spyder 2.7
I have a list: 我有一个清单:
myList = [['first'],['second'], ['third']]
and a comparison string, myStr = 'first'
和比较字符串
myStr = 'first'
I want to return True
if myStr exists in myList, else False
. 如果myStr存在于myList中,我想返回
True
,否则返回False
。
Just for the simple example you have shown, run 仅针对您显示的简单示例,运行
[myStr] in myList
But you should probably make myList
equal a flat list if each sublist contains only one item - myList = ['first', 'second', 'third']
但是,如果每个子列表仅包含一项,则应该使
myList
等于一个平面列表myList = ['first', 'second', 'third']
Then you only need 那你只需要
myStr in myList
In Python 2.7: 在Python 2.7中:
str = "first"
array = [["first"], ["second"], ...]
def isInArray(string, array):
for subarray in array:
for element in subarray:
if element == string:
return True
return False
print isInArray(str, array)
Anyway, the array makes no sense: if each subarray has only one element, you should make it easier: 无论如何,该数组毫无意义:如果每个子数组只有一个元素,则应该使它更容易:
array = ["first", "second", ...]
You need to iterate over the list with the for loop just once so that you can access the sublists 您只需要使用for循环遍历列表一次,以便可以访问子列表
myStr = 'first'
myList = [['first'],['second'], ['third']]
def str_in_list_of_lists(myStr, myList):
for i in myList:
if myStr in i:
return True
return False
print str_in_list_of_lists(myStr, myList)
Example in Python 2.7: Python 2.7中的示例:
food = [["apples", "prunes", "peaches"], ["tea", "coffee", "milk"], ["biscuits", "bread", "chips"]]
*You can try different strings here to check True/False values*
find = raw_input("What do you want in food?")
def str_in_list_of_lists(a, b):
for i in food:
if find in i:
return True
return False
print str_in_list_of_lists(find, food)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.