如何从输入中取两个数字,第一个数字表示应该有多少个列表,第二个数字表示将有多少个字符串,然后将该字符串分配给该列表的编号?例如,如果我有一个输入:
3 3 # first 3 indicates how many lists and the second 3 indicates how many strings
1 Cat # assigning Cat to the first list
2 Dog # assigning Dog to the second list
3 Tiger # assigning Tiger to the third list
它会输出:
[Cat]
[Dog]
[Tiger]
另一个输入可能是:
3 4 # 3 indicates how many lists and 4 indicates how many strings
1 Cat # assigning Cat to first list
1 Lion # assigning Lion also to first list
2 Dog # assigning Dog to second list
3 Tiger # assigning Tiger to third list
这将输出:
[Cat, Lion]
[Dog]
[Tiger]
现在我只有这个:
lst = input().split()
number = int(lst[0])
string = int(lst[1])
for k in range(number):
lst1 = []
for i in range(string):
string1 = input()
从这里开始,我对如何将字符串分配给用户输入的列表感到困惑。在我弄清楚之后,我知道如果用户决定在列表中有2个或多个字符串,我将使用append方法添加到列表中,但如果有人能帮助我如何实际分配它,我将不胜感激。
首先,我们只需输入字符串的数量和列表的数量:
n_list, n_string = [int(x) for x in input().split()]
我们创建了一个列表列表,创造性地命名为list_of_lists
,它将包含所需的n_list
列表:
list_of_lists = [[] for _ in range(n_list)]
然后,我们输入一个索引index
和字符串string
对,用空格分隔,如您在示例中所述。我们这样做n_string
次,每次都将字符串添加到通过输入index
:识别的列表中
for _ in range(n_string):
index, string = input().split()
list_of_lists[int(index) - 1].append(string)
现在,list_of_lists
包含所需的输出,您可以通过打印每个列表来检查:
for l in list_of_lists:
print(l)
这应该会产生您想要的结果
num_lists, num_strings = [int(x) for x in input().split()]
my_lists = [[] for x in range(num_lists)]
for x in range(num_strings):
index, string = input().split()
my_lists[int(index) - 1].append(string)
print(my_lists)
# 3 3
# 1 Dog
# 2 Cat
# 3 Tiger
# >>> [['Cat'], ['Dog'], ['Tiger']]
# 3 4
# 1 Cat
# 1 Lion
# 2 Dog
# 3 Tiger
# >>> [['Cat', 'Lion'], ['Dog'], ['Tiger']]
user_input = '''3 4
1 Cat
1 Lion
2 Dog
3 Tiger'''
inputs = [line.split(' ') for line in user_input.split('n')]
lists = [[] for _ in range(int(inputs[0][0]))]
for line in inputs[1:]:
lists[int(line[0]) - 1].append(line[1])
print(lists)