如何打印每个输入?

时间:2018-12-20 19:27:27

标签: python python-3.x

我想使用数组和输入编写代码,然后将列表从16岁以上的人和16岁以下的人中分离出来,但是似乎无法获得打印每个输入的代码。它只想打印我所做的最后一个输入。这是我到目前为止的内容:

A = [0 for x in range (10)]
B = [0 for x in range (10)]

for i in range (10):
    A[i] = input('enter A name: ')
    B[i] = input('enter the age to go with the name: ')
    print()
    B2 = int(B[i])

if B2 > 16:
    print(B2, A[i])

if B2 < 16:
    print(A[2], B2)

3 个答案:

答案 0 :(得分:1)

这是因为if条件在for循环之外,所以您正在覆盖B2。每次B2都会被输入用户提供的内容覆盖。我不知道你要在印刷部分做什么。但是将其放入循环应该可以解决问题。

答案 1 :(得分:1)

这是因为,在for循环(B2B2 = int(B[i])的每一次迭代中,您要覆盖i行中的for i in range (10):,下面的代码应该起作用:

A , B = [], []

for i in range(10):
    A += [raw_input('enter A name: ')]
    B += [input('enter the age to go with the name: ')]
    print()    

for i in range(len(B)):    
    if B[i] >= 16: print(B[i], A[i])        

    if B[i] < 16: print(A[i], B[i]) 

在上面的代码A中是一个列表,将所有名称存储为字符串。 B是另一个列表,将所有年龄段存储为int数据类型。

print A
>>>['Name1', 'Name2', 'Name3', 'Name4', 'Name5', 'Name6', 'Name7', 'Name8', 'Name9', 'Name10']       

print B
>>>[18, 10, 19, 5, 55, 12, 6, 66, 14, 7]       

答案 2 :(得分:1)

您的代码确实忽略了16岁的孩子,并且还有其他一些问题。

您可以在输入到两个单独的列表(under_16over_15)之后直接过滤输入,也可以将所有内容都放入一个列表(all_studs),然后稍后使用{{ 3}}或list comprehensions

under_16 = []  # immediatly sorted
over_15 = []   # immediatly sorted
all_studs =[]  # all of them

for i in range (10):
    name = input('enter A name: ')
    while True:
        # avoid input of "ten" when age is asked - ask until valid
        try:
            age = int(input('enter the age to go with the name: '))  
            break
        except Exception: 
            print("Try again - input age. Hint: a _number_")

    # add all to big list
    all_studs.append((name,age))

    # sort immediately on input
    if age < 16:
        under_16.append( (name,age))
    else:
        over_15.append( (name,age))

# get from list by list-comp: 
under = [ (name,age) for name,age in all_studs if age < 16 ]
over =  [ (name,age) for name,age in all_studs if age >= 16 ]

# get from list by filter:
un = list(filter(lambda x:x[1]<16,all_studs))
ov = list(filter(lambda x:x[1]>15,all_studs))

print(un)        
print(ov)       

print(under)     
print(over)      

print(under_16)  
print(over_15)   

print(all_studs) 

输出(对于输入Phil,2,A,19,B,18,C,17,D,16,E,15,F,14,G,13,H,12,I,11,J,10):

# un, under, under_16
[('Phil', 2), ('E', 15), ('F', 14), ('G', 13), ('H', 12), ('I', 11)]

# ov, over, over_15
[('A', 19), ('B', 18), ('C', 17), ('D', 16)]

# all_studs 
[('Phil', 2), ('A', 19), ('B', 18), ('C', 17), ('D', 16), ('E', 15), 
 ('F', 14), ('G', 13), ('H', 12), ('I', 11)]