简体   繁体   English

如何从整数列表中删除所有字符串元素,字符串旁边是整数 [Python]

[英]How to remove all string elements from a list of integers, with strings next to integers [Python]

I have a list:我有一个清单:

['6.26%', '5.94%', '7.47%', '6.90%', '5.99%', '7.94%', '8.75%', 
 '9.01%', '10.07%', '5.51%', '4.87%', '5.88%', '4.26%', '2.97%', 
 '6.38%', '4.93%', '3.96%', '4.62%', '3.73%', '5.15%', '0.86%', 
 '2.68%', '4.01%', '4.89%', '5.84%', '5.23%', '5.57%', '5.53%', 
 '2.39%', '1.00%', '2.44%', '4.65%', '3.66%', '4.60%', '4.54%', 
 '2.30%', '-1.51%', '2.36%', '3.13%', '3.12%', '1.28%', '3.55%', 
 '3.48%', '1.13%', '3.45%']

and I would like to remove all the ' and % from the list to give me a list with integers that I can use to add to another list.并且我想从列表中删除所有 ' 和 % 以给我一个包含整数的列表,我可以用它来添加到另一个列表中。 I have seen and looked at many questions regarding lists but none seem to apply to my scenario.我已经看到并查看了许多关于列表的问题,但似乎没有一个适用于我的场景。 Help please!请帮忙!

Just use a list comprehension只需使用列表理解

values_list = ['6.26%', '5.94%', '7.47%', '6.90%', '5.99%', '7.94%', 
'8.75%', '9.01%', '10.07%', '5.51%', '4.87%', '5.88%', '4.26%', 
'2.97%', '6.38%', '4.93%', '3.96%', '4.62%', '3.73%', '5.15%', 
'0.86%', '2.68%', '4.01%', '4.89%', '5.84%', '5.23%', '5.57%', 
'5.53%', '2.39%', '1.00%', '2.44%', '4.65%', '3.66%', '4.60%', 
'4.54%', '2.30%', '-1.51%', '2.36%', '3.13%', '3.12%', '1.28%', 
'3.55%', '3.48%', '1.13%', '3.45%']

float_list = [float(value.strip('%')) for value in values_list]

This results in:这导致:

[6.26, 5.94, 7.47, 6.9, 5.99, 7.94, 8.75, 9.01, 10.07, 5.51, 4.87, 
 5.88, 4.26, 2.97, 6.38, 4.93, 3.96, 4.62, 3.73, 5.15, 0.86,
 2.68, 4.01, 4.89, 5.84, 5.23, 5.57, 5.53, 2.39, 1.0, 2.44, 4.65, 
 3.66, 4.6, 4.54, 2.3, -1.51, 2.36, 3.13, 3.12, 1.28, 3.55, 
 3.48, 1.13, 3.45]

A simple way (but more inefficient).一种简单的方法(但效率更低)。 Remove every % from the string using a for loop.使用 for 循环从字符串中删除每个 %。 Then you can convert them into floats.然后您可以将它们转换为浮点数。 For example:例如:

l = ['6.26%', '5.94%',  '7.47%', '6.90%', '5.99%', '7.94%', '8.75%', 
'9.01%', '10.07%', '5.51%', '4.87%', '5.88%', '4.26%', '2.97%', 
'6.38%', '4.93%',  '3.96%', '4.62%', '3.73%', '5.15%', '0.86%', 
'2.68%', '4.01%',  '4.89%', '5.84%', '5.23%', '5.57%', '5.53%', 
'2.39%', '1.00%',  '2.44%', '4.65%', '3.66%', '4.60%', '4.54%', 
'2.30%', '-1.51%', '2.36%', '3.13%', '3.12%', '1.28%', '3.55%', 
'3.48%', '1.13%',  '3.45%']
new = []
for item in l:
    new.append(float(l[:-1]))
l = new

new now equals your wanted list新现在等于你的通缉名单

EDIT: The int() function should actually be float().编辑: int() 函数实际上应该是 float()。 This will result in the strings not losing their decimal values.这将导致字符串不会丢失其十进制值。

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

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