在Python中剥离列表 [英] Strip a list in Python
问题描述
我在python中有一个列表,它是由许多函数产生的.它是这样产生的:
I have a list in python which is produced from a number of functions. It is produced like this:
['01', '1.0', '[0.2]']
我想在生成所有不需要的字符后将其删除.
I would like to strip all of the unnecessary characters after it is produced.
理想的输出:
['01', '1.0', '0.2']
我基本上需要从列表中的最后一个字符串中删除[和].
I basically need to remove the [ and ] from the final string in the list.
更新:
list_test = ['01', '1.0', '[0.2]']
[i.strip('[]') if type(i) == str else str(i) for i in list_test]
print(list_test)
无论有没有产生相同的结果,这都不起作用:
This doesn't work as both with and without produce the same result:
['01', '1.0', '[0.2]']
所需的结果是:
['01', '1.0', '0.2']
提供的解决方案:
l = ['01', '1.0', '[0.2]']
[i.strip('[0.2]') if type(i) == str else str(i) for i in l]
print(l)
输出:
['01', '1.0', '0.2']
Process finished with exit code 0
推荐答案
如果你只需要删除一个可选的 [
和 ]
围绕一个字符串,这个单行应该做到这一点:
If you just need to remove an optional [
and ]
around a string, this one-liner should do the trick:
l = [i.strip('[]') for i in l]
以您的示例
>>> l = ['01', '1.0', '[0.2]']
>>> [i.strip('[]') for i in l]
['01', '1.0', '0.2']
它的作用:遍历列表的所有字符串,并删除所有 [
和]
(如果它们位于字符串的开头或结尾).它还会将] 0.2 [
变成 0.2
.
What it does: it iterates over all strings of the list and removes any [
and ]
if they are at the beginning or end of the string. It also would make ]0.2[
into 0.2
.
更新:
我得到
AttributeError:'int'对象没有属性'strip'
在这种情况下,您的输入数组中有一个int,这个衬里应该可以解决问题:
In this case you have an int in your input array, this one liner should do the trick:
l = [i.strip('[]') if type(i) == str else str(i) for i in l]
以一个带有int的示例为例:
With an example with an int:
>>> l = ['01', '1.0', '[0.2]', 2]
>>> [i.strip('[]') if type(i) == str else str(i) for i in l]
['01', '1.0', '0.2', '2']
它是做什么的
- 仅从字符串中剥离
[
和]
- 将非字符串的所有内容转换为字符串
这篇关于在Python中剥离列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!