简体   繁体   English

如何将每个新输入放入python中的新列表中?

[英]How to put every new input into a new list in python?

I want it to be so that once the user input's their inputs, they both will go into a new list.我希望它一旦用户输入是他们的输入,他们都会进入一个新列表。

num = int(input("Choose a number"))

for i in range(num):
    input1, input2 = input("").split()

For each input1 and input2, I want it go into an entirely new list.对于每个 input1 和 input2,我希望它进入一个全新的列表。 For example: If I input num as 3, I would have to input, input1 and input 2, three times.例如:如果我输入 num 为 3,我将不得不输入、输入 1 和输入 2 三次。 I want three different lists then for that case containing just input 1 and input2.我想要三个不同的列表,然后对于只包含输入 1 和输入 2 的情况。

Input: 
>> Choose a number 3
>> 4 5
>> 3 6
>> 2 2

Output: 
>> [4,5] 
>> [3,6]
>> [2,2]

Just to clarify, the "choose a number" input is entirely based on input.只是为了澄清,“选择一个数字”输入完全基于输入。 This means that "x" number of lists should be created with input1 and input2 based on the choose a number input (x)这意味着应该根据选择一个数字输入 (x) 使用 input1 和 input2 创建“x”个列表

  • you can use list of lists to store the results:您可以使用列表列表来存储结果:
num = int(input("Choose a number"))
res = [] # this will store all user inputs.
for i in range(num):
    input1, input2 = input("").split()
    res.append([input1, input2])

print(*res, sep='\n')

output输出


Choose a number 3
 5 2
 4 2
 6 56
['5', '2']
['4', '2']
['6', '56']
  • solution 2:解决方案2:
num = int(input("Choose a number"))
res = dict() # this will store all user inputs.
for i in range(num):
    res['user'+str(i)] = input("").split()
print(res['user1'])
  • output:输出:
Choose a number 3
 2 5
 2 5
 36 663
['2', '5']

You can do it that way, for example:你可以这样做,例如:

num = int(input("Choose a number"))

temp = []
for _ in range(num):
    input1, input2 = input().split()
    temp.append([input1, input2])
    print(temp); temp = []

You need to have a main list, then add your sublist (splitted input) into it :您需要有一个主列表,然后将您的子列表(拆分输入)添加到其中:

num = int(input("Choose a number"))
values = []
for _ in range(num):
    values.append(input("").split())

print(values) # [[4,5], [3,6], [2,2]]
print(values[1]) # [3,6]

Using a list-comprehesion, the same is使用列表理解,同样是

values = [input("").split() for _ in range(num)]

Do the following, to get each sublist on a new line执行以下操作,将每个子列表放在一个新行上

print(*values, sep='\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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