我正在尝试编写一个函数,该函数将搜索列表列表以查找用户给出的单词或片段,并返回包含该单词的所有单元。
这是我到目前为止所拥有的:
def cat(dogs):
"""
searches for cat names in dogs
"""
search = raw_input("search for: ")
word = search[0].upper() + search[1:]
for i in range(len(dogs)):
if word in dogs[i]:
print "yes"
else:
print "sorry, nothing found"
return
我该如何解决这个问题?
非常感谢!!
答案 0 :(得分:0)
我建议您在搜索过程中将stockdata
中的字符串和字符串转换为大写,以便能够同时检测到Computer
和computer
如果未找到任何结果,您还应该打印sorry, not found
我已添加results
变量以查看搜索结果。
def company(stockdata):
"""
searches for companies with the word inputted and gives back full
company names and ticker tags
"""
found = False
results = []
search = raw_input("search for: ")
word = search.upper()
for i in range(len(stockdata)):
if word in stockdata[i][0].upper() or word in stockdata[i][1].upper(): # I've used stockdata[i][0] because the string is in a list of list
found = True
results.append(stockdata[i][0])
if found:
print 'yes'
print 'results : ',results
else:
print "sorry, nothing found"
stock = [['AAME', 'Atlantic American Corporation', '2013-11-04', 4.04, 4.05, 4.01, 4.05, 5400.0, 4.05], ['AAON', 'AAON Inc.', '2013-11-04', 27.28, 27.48, 27.08, 27.32, 96300.0, 27.32], ['AAPL', 'Apple Inc.', '2013-11-04', 521.1, 526.82, 518.81, 526.75, 8716100.0, 526.75], ['AAWW', 'Atlas Air Worldwide Holdings', '2013-11-04', 38.65, 39.48, 38.65, 38.93, 490500.0, 38.93], ['AAXJ', 'iShares MSCI All Country Asia ex Japan Index Fund', '2013-11-04', 60.55, 60.55, 60.3, 60.48, 260300.0, 60.48], ['ABAX', 'ABAXIS Inc.', '2013-11-04', 36.01, 36.91, 35.89, 36.2, 208300.0, 36.2]]
company(stock)
生成: 搜索字词 abaxis
yes
results : ['ABAX']
注意:请提供您的库存数据列表示例,如果可能的话,该列表会传递给该函数以确保其正常工作
答案 1 :(得分:0)
'''
searches for companies with the word input and gives back full
company names and ticker tags
'''
def company(stockdata):
searchString = raw_input("search for: ")
flatList = [item.upper() for sublist in stockdata for item in sublist]
if any(searchString.upper() in s for s in flatList):
print "Yes"
else:
print "sorry, nothing found"
答案 2 :(得分:0)
如果您要搜索列表列表,除非我误解了您的问题,否则您需要另一个for
循环。到目前为止,K DawG给出了最好的答案。不幸的是,我不能赞成它。
def company(stockdata):
search = raw_input("search for: ")
word = search.upper()
for i in range(len(stockdata)):
for j in range(len(stockdata[i])):
if word in stockdata[i][j].upper():
print stockdata[i][j]
else:
print "sorry, nothing found"
return
data = [["computer", "cheese"], ["apple"], ["mac Computers"]]
company(data)
返回:
computer
sorry, nothing found
sorry, nothing found
mac Computers