我有这些清单:
array = ['I love school', 'I hate school', 'I hate bananas', 'today is
friday', 'worldcup is great']
#finalArray is initially an empty list
finalArray = []
我想将包含单词“school”的“array”索引保存到“finalArray”中。意思是“finalArray”应该变成这样:
['I love school', 'I hate school']
我尝试了以下不执行此操作的代码:
if "school" in array:
finalArray = array.index("school")
为什么不起作用?有一个更好的方法吗?
您的解决方案无效,因为您正在检查示例数组中的“school”字样。要完成你想要的,你必须遍历列表并检查每个元素是否包含'school':
array = ['I love school', 'I hate school', 'I hate bananas', 'today is friday', 'worldcup is great']
finalArray = []
for element in array:
if 'school' in element.lower():
finalArray.append(element)
请注意,我在每个已检查元素中添加了一个lower(),以确保您的程序还会在输入列表中捕获“School”。
您需要遍历数组,查看目标字school
是否在该数组元素中。然后将索引放入列表中。
final_array = [i for i in range(len(array)) if "school" in array[i]]
输出:
[0, 1]
你最初的尝试没有这样做:index
可以在一个句子中找到school
的位置,而不是在数组中包含school
的句子的位置。
使用更多Pythonic技术进行改进:
[i for i, phrase in enumerate(array) if "school" in phrase]
您可以检查当前迭代元素中是否存在"school"
:
array = ['I love school', 'I hate school', 'I hate bananas', 'today is friday', 'worldcup is great']
new_array = [i for i in array if "school" in i]
输出:
['I love school', 'I hate school']
enumerate
是提取指数的一种Pythonic解决方案:
arr = ['I love school', 'I hate school', 'I hate bananas',
'today is friday', 'worldcup is great']
res = [i for i, j in enumerate(arr) if 'school' in j]
# [0, 1]
如果你想要值,逻辑就更简单了:
res = [i for i in arr if 'school' in i]
# ['I love school', 'I hate school']
列表推导提供与通过for循环追加到列表相同的结果,除非它是高度优化的。
为什么不起作用?
因为index(x)方法,根据官方Python 3文档:
返回最小的i,使得i是数组中第一次出现x的索引。
所以,如果你想要finalArray = ['I love school', 'I hate school']
,你不需要索引(整数),但你想要实际的项目(在这种情况下是一个字符串)。
有一个更好的方法吗?
您可以简单地遍历array
的元素(字符串),如果字符串包含单词“school”,您可以将其添加到finalArray
。
array = ['I love school', 'I hate school', 'I hate bananas', 'today is friday', 'worldcup is great']
finalArray = []
for element in array: # for each element in the array
if "school" in element: # check if the word "school" appears in the "element" string variable
finalArray.append(element) # if yes, add the string to "finalArray" variable
注意:这不是Pythonic代码的目的。 Delirious Lettuce's answer包含一种Pythonic方式。
我想知道没有人推出内置functionfilter
的解决方案:
>>> array = ['I love school', 'I hate school', 'I hate bananas', 'today is friday', 'worldcup is great']
>>> list(filter(lambda el: 'school' in el, array))
['I love school', 'I hate school']