如何使用Python中的数组从用户输入字符列表

时间:2019-03-29 06:43:37

标签: python arrays

我正在尝试构建一个基本程序,该程序将从用户那里获取名称并显示包含5个以上字母的名称的数量。

from array import*

list=array('u',[])

n=int(input("Enter the number of names first"))

for i in range(0,n):

    y=input("Enter the names one by one")
    list.append(y)

但是运行此代码时出现错误

  

“ TypeError:数组项必须为Unicode字符”

2 个答案:

答案 0 :(得分:1)

从评论继续,请保持简洁以方便您理解:

n = int(input("Enter the number of names first"))

nameLst = []           # an empty list to store the desired names
for i in range(0,n):
    y = input("Enter the names one by one")     
    if len(y) > 5:               # if the len of name is > 5
        nameLst.append(y)        # append it to the list

for i in range(len(nameLst)):    # iterate over the len of the list
    print(nameLst[i])            # print all the names in the list

答案 1 :(得分:1)

n=int(input('enter times : '))
name =list(map(str, input("enter name spe by space : ").strip().split()))
if len(name)==n:
    name2 =[i for i in name if len(i)>=5]
    print("name are ->", *name2)

"""
output 

enter times : 3

enter name spe by space : john edward philips
name are -> edward philips

"""