[英]How to iterate over each element in a list?
I have a list of strings and I am iterating over each element by using a for
loop, but it seems that what I am doing is iterating over each character instead of each element of the list. 我有一个字符串列表,并且正在使用
for
循环遍历每个元素,但是似乎我正在做的是遍历每个字符而不是列表中的每个元素。 For instance: 例如:
names = list(input('Enter list of names:')).upper()))
result = []
for i in names:
if 'A' not in i and 'C' in i:
result.append('membership')
elif 'A' in i and 'C' not in i:
result.append('no_membership')
else:
result.append('unknow'):
print(result)
But what I am getting is a list in which the for
loop is evaluating each character in the list of strings instead of each name. 但是我得到的是一个列表,其中
for
循环正在评估字符串列表中的每个字符而不是每个名称。 Am I doing something wrong in the code or do I need to split the elements of the list? 我在代码中做错了吗?还是需要拆分列表中的元素?
Logically you are just trying to add the entire input into one item of the list 从逻辑上讲,您只是想将整个输入添加到列表的一项中
So the first line should read something like: 因此,第一行应显示为:
names = input('Enter list of names:').upper().split()
This will split the inputted string by spaces into a list of separate strings. 这会将输入的字符串按空格分隔成单独的字符串列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.