簡體   English   中英

在Python中將帶小數位的字符串列表轉換為整數

[英]Converting list of strings with decimal places to ints in python

example_list = ['21.48678', '21.46552', '21.45145', '21.43822',
                '21.42734', '21.41222', '21.40132', '21.37679']

我在將此列表從字符串轉換為整數時遇到麻煩,我也希望將其作為整數。 謝謝 :)

最簡單的是

[int(float(x)) for x in your_list]

這將截斷所有數字

如果要四舍五入,請改用此方法

[int(float(x)+.5) for x in your_list]

首先轉換為float

>>> lst = ['21.48678', '21.46552', '21.45145', '21.43822', '21.42734', '21.41222', '21.40132', '21.37679']
>>> ints = [int(float(num)) for num in lst]
[21, 21, 21, 21, 21, 21, 21, 21]
foo = ['21.48678', '21.46552', '21.45145', '21.43822', '21.42734', '21.41222', '21.40132', '21.37679']

map(lambda x: int(float(x)), foo)
[int(round(float(i))) for i in example_list]

將列表中的項目轉換為float ,將其舍入 ,然后將其轉換為int

new_list=[]
for each in example_list:
    Integer = int(each)
    new_list.append(Integer)
print new_list

這對於初學者來說很容易理解:D

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM