I am currently trying to append both integers and strings, which I am trying to turn into integers, as they can only be numbers separated by space. My current code:
def check(x):
if type(x) == str:
x = x.split()
return x
else:
return x
Data = []
while True:
try:
numbers = input()
if numbers !='':
added = check(numbers)
Data.append(added)
else:
print(Data)
break
except EOFError as error:
print(Data)
break
but that does not exactly do what I need. For example inputs of
1
22
1 2 3
Give me the output of
[['1'], ['22'], ['2', '3', '4']]
While I desire the output of
[['1'], ['22'], ['2'], ['3'], ['4']]
Replace
Data.append(added)
with
for d in added:
Data.append([d])
then
1
22
2 3 4
[['1'], ['22'], ['2'], ['3'], ['4']]
Above is good but this code also help you do your task
Data = []
while True:
try:
numbers = list(map(int,input().split()))
if len(numbers)==0:
print(Data)
break
else:
Data.append(numbers)
except:
print(Data)
This also when we give input
2
22
1 2 3 4
When you don't give anything as input like a simple enter will break the infinite loop and then gives you the following output.. I think that function is really redundant!. The output is
[[2],[22],[1,2,3,4]]
Hope this helps: Happy Learning:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.