简体   繁体   English

如何遍历列表中的每个元素?

[英]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.

相关问题 如何迭代后缀列表以添加到列表中每个变量的末尾? - How to iterate over a list of suffixes to add to the end of each variable in a list? 如何遍历列表中的每两个元素,python3? - How to iterate over each 2 elements in a list, python3? 如何迭代/循环列表并引用前一个(n-1)元素? - How to iterate/loop over a list and reference previous (n-1) element? 如何在将列表中的每个值传递到 API 并在每个列表列表后暂停时迭代列表列表? - How to iterate over list of lists while passing each value in the lists into API and pausing after each list of list? 遍历列表以将方法应用于每个成员 - Iterate over a list to apply a method to each member 遍历列表并依次 append 每个元素到一组新列表 - Iterate over list and sequentially append each element to a set number of new lists pandas dataframe 迭代作为列表的单元格值并将每个元素与其他单元格进行比较 - pandas dataframe iterate over cell value that is a list and compare each element to other cell 如何迭代python列表? - How to iterate over a python list? 如何遍历list并将每个元素作为包含自身作为唯一元素的list传递? - How to iterate through list and pass each element as list containing itself as the only element? 迭代第一个列表[]中的每个值到另一个列表[]上以形成字典{} - Iterate each value in the first list [] over another list [] to form dictionary {}
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM