简体   繁体   中英

Python Input Decimal Numbers and Whole Numbers (Float)

I would like to have an input where I can input numbers such as 8 8.5 7 3 4 5.5 8 9 10.5 and into a list.

I have tried the code below, but:

my input:

Sizes: 9.5 9 10 10.5 3 4 8 7.5

my out put:

[9.5, 9.0, 10.0, 10.5, 3.0, 4.0, 8.0, 7.5]

my desired out put:

[9.5, 9, 10, 10.5, 3, 4, 8, 7.5]

select_sizes = [float(x) for x in input('Sizes: ').split()]
print(select_size)

i have this list that i have scraped ----- size_ids list : ['91|10.5', '150|9.5', '28|4', '29|5', '22|8', '23|9', '24|10', '25|11', '26|12'] --------- example of inputted list: [5, 5.5, 6, 7, 8.5, 10.5] and basically i want to use the list that i have inputted and if the size_ids list above matches with the first thing in the inputted list, it gets that number in the size_ids list as fsize.

[float(x) if '.' in x else int(x) for x in input('Sizes: ').split()]

那就是您想要的,但是在列表中混合使用不同的类型并不是一件好事,实际上您可以使用浮点数,并且不会停止任何操作。

If you want only the formatting, you can use a %g specifier for printing floats without trailing 0s (it's not a good idea to store a mix of floats and integers):

print(", ".join("%g" % x for x in select_size))

will print

9.5, 9, 10, 10.5, 3, 4, 8, 7.5

Of course, you can optionally include square brackets by manually appending them to the resulting string (but do you really need it?)

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