[英]How to compare string vs. list of lists in Python/Spyder 2.7
我有一個清單:
myList = [['first'],['second'], ['third']]
和比較字符串myStr = 'first'
如果myStr存在於myList中,我想返回True
,否則返回False
。
僅針對您顯示的簡單示例,運行
[myStr] in myList
但是,如果每個子列表僅包含一項,則應該使myList
等於一個平面列表myList = ['first', 'second', 'third']
那你只需要
myStr in myList
在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)
無論如何,該數組毫無意義:如果每個子數組只有一個元素,則應該使它更容易:
array = ["first", "second", ...]
您只需要使用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)
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.