简体   繁体   中英

Python - How do I append numbers inside the list and

Whenever I try appending numbers from my input to my list, it goes outside one of the brackets instead of inside the two brackets

Is there a way to only have one pair of brackets instead of two?

Also I am trying to add random numbers between 1-3 and i get,

[[2, 1, 3]]

How can you create random numbers in the tenths decimal place

My Code,

import random
array = []

nums = random.sample(range(1, 4), 3)
array.append(nums)
print(array)

for x in range(2):
    nums = int(input("what are your numbers "))
    array.append(nums)
    print(array)

I get,

[[2, 1, 3]]
what are your numbers 3
[[2, 1, 3], 3]
what are your numbers 2
[[2, 1, 3], 3, 2]

Process finished with exit code 0

random.sample() is already returning list as return value to you so there is no need to append it to another one

array = random.sample(range(1, 4), 3)

In your code

import random

array = random.sample(range(1, 4), 3)

print(array)

for x in range(2):
    number = int(input("what are your numbers "))
    array.append(number)
    print(array)

You first let the nums be a list nums = random.sample(range(1, 4), 3) . Thus if you append nums to array .So the array becomes a list that contains other lists instead of integer.

May be you could just simply try array = random.sample(range(1, 4), 3) .It will let array to be a list of integer,then append other numbers you need.:D

There is actually another way to do what you want,just array += random.sample(range(1, 4), 3) it will make the content in random.sample appended into the array instead of being append as a list.

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.

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