如何将 for 循环中的用户输入保存为整数和字符串

How to save user inputs in a for loop as an integer and string

用户想要输入如下数据,并将 N 保存为整数列表,将 B 保存为字符串列表。

输入:

2
hello world
3
how are you
5
what are you doing man

然后我想像下面这样保存这两个列表:

N=[2,3,5]
B=['hello world','how are you','what are you doing man']

我从下面的代码开始,但我不确定如何将它放在一个循环中以保存所有代码。

N=list(map(int, input()))
B = list(map(str, input().split())) 

您可以执行以下操作:

N, B = lists = [], []

for i in range(6):
    lists[i%2].append(input())

N = list(map(int, N))

或者,也许不那么神秘:

aux = [input() for _ in range(6)]

N = list(map(int, aux[::2]))
B = aux[1::2]

一种方法非常简单明了。 while 循环可用于保持提示滚动,直到给出一个存在的命令(在本例中为:x)。

示例:

N, B = [], []

while True:
    print('Enter an integer, then string (or [x] to exit):')
    n = input()
    if n != 'x':
        N.append(int(n))
        B.append(input())
    else:
        break

提示:

Enter an integer, then string (or [x] to exit):
5
Hello.
Enter an integer, then string (or [x] to exit):
15
How are you?
Enter an integer, then string (or [x] to exit):
20
Very well, thank you.
Enter an integer, then string (or [x] to exit):
x

输出:

N
>>> [5, 15, 20]

B
>>> ['Hello.', 'How are you?', 'Very well, thank you.']

实时python记事本怎么样:

N = []
B = []
i = 0
while True:
    lst = B if i % 2 else N
    i += 1
    text = input()
    lst.append(text)
    if lst:
        if not text and not lst[-1]:
            lst.pop()
            break
N = list(map(int, N))
print(N)
print(B)

简单地运行上面的代码,然后键入直到您按两次没有其他字符的回车键。 输入:

2
hello world
3
how are you
5
what are you doing man

输出:

[2, 3, 5]
['hello world', 'how are you', 'what are you doing man']