简体   繁体   中英

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 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM