I have a list:
myList = [['first'],['second'], ['third']]
and a comparison string, myStr = 'first'
I want to return True
if myStr exists in myList, else 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']
Then you only need
myStr in myList
In 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
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:
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)
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.