Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将for循环中的用户输入保存为整数和字符串_Python_String_List_For Loop_User Input - Fatal编程技术网

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

Python 如何将for循环中的用户输入保存为整数和字符串,python,string,list,for-loop,user-input,Python,String,List,For Loop,User Input,用户希望输入如下所示的数据,并将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(

用户希望输入如下所示的数据,并将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
循环保持提示滚动,直到发出exist命令(在本例中为:
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.']
[2, 3, 5]
['hello world', 'how are you', 'what are you doing man']

一个实时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)
只需运行上面的代码,然后键入,直到按ENTER键两次,不使用其他字符。 输入:

输出:

N
>>> [5, 15, 20]

B
>>> ['Hello.', 'How are you?', 'Very well, thank you.']
[2, 3, 5]
['hello world', 'how are you', 'what are you doing man']