基本上,我希望我的代码能够搜索列表中的特定字符,然后根据是否找到该字母将其附加到另一个列表中。到目前为止,这是我的代码,但是列表没有正确地追加
list2=["apple","bannana","lychee","pear","red"]
list3=[]
list4=[]
j=0
for word in list2[:]:
if 'R'or'Y'or'I' in word:
list3.append(list2[j])
j+=1
else:
list4.append(list2[j])
j+=1
print(list3)
print(list4)我的产出是:“苹果”、“班纳纳”、“荔枝”、“梨”、“红色”。
发布于 2021-12-16 18:53:11
您的单个数组元素需要在引号中。它会是
list2=[“apple”, ”banana”, ”lychee”, ”pear”, “red”]您也需要搜索小写,因为您只是在搜索大写字母。
发布于 2021-12-18 08:37:55
(假设您在使用python,但这些方法在其他语言中也或多或少适用)
item变量。[:]),当您不想要子列表时,可以使用列表本身。or条件是1. `'R'`
2. `'Y'`
3. `'I' in word`由于真与假值的概念,前两个计算值为true,因此即使'I' in word为false,'R'和'Y'为true,true or true or false为真,因此if块总是被求值。
in检查区分大小写,因此需要使用小写字母检查条件。应用所有这些,所需的代码如下所示:
list2 = ["apple","bannana","lychee","pear","red"]
list3 = []
list4 = []
for word in list2:
if 'r' in word or 'y' in word or 'i' in word:
list3.append(word)
else:
list4.append(word)
print(list3)
print(list4)输出:
['lychee', 'pear', 'red']
['apple', 'bannana']https://stackoverflow.com/questions/70384166
复制相似问题