Multiple inputs from one input

I am writing a function to add input to a list. When I enter 280 2 , I want the list to become ['280', '280'] instead of ['280 2'] .

+5
source share
4 answers
 >>> number, factor = input().split() 280 2 >>> [number]*int(factor) ['280', '280'] 

Remember that combining a list with itself with the * operator may have unexpected results if your list contains mutable elements, but in your case this is normal.

edit:

A solution that can handle inputs without a factor:

 >>> def multiply_input(): ... *head, tail = input().split() ... return head*int(tail) if head else [tail] ... >>> multiply_input() 280 3 ['280', '280', '280'] >>> multiply_input() 280 ['280'] 

Add error checking as necessary (for example, for empty inputs) depending on your use case.

+8
source
 from itertools import repeat mes=input("please write your number and repetitions:").split() listt= [] listt.extend(repeat(int(mes[0]), int(mes[1])) #repeat(object [,times]) -> create an iterator which returns the object #for the specified number of times. If not specified, returns the object #endlessly. 
+2
source

You can handle the case with an unspecified number of repetitions by expanding the parsed input using a list containing 1. Then you can cut the list to leave the first 2 elements (in case the number of repetitions was specified, [1] will be discarded)

 number, rep = (input().split() + [1])[:2] [number] * int(rep) 
+2
source

This code provides exception handling since the second number is not provided in put.

 def addtolist(): number = input("Enter number: ") try: factor = input("Enter factor: ") except SyntaxError: factor = 1 for i in range(factor): listname.append(number) 
0
source

Source: https://habr.com/ru/post/1247258/


All Articles