简体   繁体   English

Python 更改格式时更改列表的顺序

[英]Python changing order of a list when I change the formatting

I am trying to change the format of all items in my list from float to integer.我正在尝试将列表中所有项目的格式从浮动更改为 integer。 My code seem to do the job, however it is changing the order of the items in the list.我的代码似乎可以完成这项工作,但是它正在更改列表中项目的顺序。

A reproducible example:一个可重现的例子:

l = [-1.0, 0.0, 1.0]
[int(f'{float(l[int(i)]):g}') for i in l]

>>> Out: [1, -1, 0]

Any idea how to avoid the re-arrangement of these elements?知道如何避免这些元素的重新排列吗?

Thank you.谢谢你。

l[int(i)]) <- you're accessing the list positions by index here. l[int(i)]) <- 您在此处按索引访问列表位置。 Just re-write your code using map:只需使用 map 重写您的代码:

l = [-1.0, 0.0, 1.0]
o = list(map(int, l))
print(o)

Output: Output:

[-1, 0, 1]

You are overthinking this, simply do:您想多了,只需执行以下操作:

l = [-1.0, 0.0, 1.0]
[int(i) for i in l]

You could use both comprehension list and functional programming:您可以同时使用理解列表和函数式编程:

l = [-1.0, 0.0, 1.0]
result1 = [int(i) for i in l]
result2 = list(map(int, l))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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