Home > database >  How do I assign a string to a list of which the number that the user inputs?
How do I assign a string to a list of which the number that the user inputs?

Time:10-27

How do I take 2 numbers from input where the first number indicates how many lists there should be and the second indicates how many strings there will be and then assigning that string to the number of that list? For example if I have an input of:

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

It would ouput:

[Cat]
[Dog]
[Tiger]

Another input could be:

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

And that would output:

[Cat, Lion]
[Dog]
[Tiger]

Right now all I have is this:

lst = input().split()
number = int(lst[0])
string = int(lst[1])

for k in range(number):
    lst1 = []
for i in range(string):
    string1 = input()

From here I'm confused on how to assign the string to the list that the user inputs. After I figure that out I know I'll have use the append method to add to the list if the user decides to have 2 or more strings in a list but if someone could help me out on how to actually assign it, I'd appreciate it.

CodePudding user response:

This should produce the result you want

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']]

CodePudding user response:

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)
  • Related