我有一个长列表,里面有很多单词,我想创建一个只包含单词的新列表以";a";。
list_1 = []
for i in range(len(words) - 1):
if words[0: len(words) - 1][0] == "a":
list_1.append(words)
print(list_1)
您可以使用startswith
list_1 = [x for x in words if x.startswith('a')]
尝试:
list_1= [word for word in words if word[0] =='a']
方法1-
list_1 = []
for i in range(len(words) - 1):
if words[i][0] == "a":
list_1.append(words)
print(list_1)
方法2
list_1= [word for i in words if word[0] =='a']
old_list = ['hello', 'world', 'alike', 'algorithm']
new_list = [i for i in old_list if i.startswith('a')]
现在打印new_list将给出[类似,算法]
查看
for i in range(len(words) - 1):
if words[0] == "a":
list_1.append(words)
print(list_1)