【问题标题】:How to remove a string from a list python如何从列表python中删除字符串
【发布时间】:2019-02-25 21:03:28
【问题描述】:

是否可以删除字符串并只保留列表

data = [
"50,bird,corn,105.4,"
"75,cat,meat,10.3,"
"100,dog,eggs,1000.5,"
]

希望它看起来像这样

data = [
50,'bird','corn',105.4,
75,'cat','meat',10.3,
100,'dog','eggs',1000.5,
]

【问题讨论】:

  • 你尝试了什么,遇到了什么问题?
  • data 中的列表格式不正确。您是如何得出初始数据结构的?
  • 我尝试 data[1].strip("") 不起作用 - 不确定可以使用什么
  • input = open(data.txt, 'r') data = input.read().splitlines()
  • words = ','.join(data).split(',') 在修复了你的data 之后(这是一种懒惰的做法 - 它在由 分隔的大字符串上创建,然后在 , 处分割 - 效果不如发布的答案)跨度>

标签: python string list


【解决方案1】:
out = []
for x in data:
  for e in x.split(","):
    out.append(e)

这是做什么的?它用逗号分割data 中的每个元素(x),挑选出每个单独的标记(e),并将它们放入变量(out.append)中。

【讨论】:

  • 感谢您的帮助,但这是在“,”处拆分数据,但我只是想删除此封装“”
【解决方案2】:
new_data = []
for i in data:
    new_data.extend(i.split(','))
new_data

请注意可能存在问题(例如,最后一个逗号后面没有任何内容,因此它会生成一个 '' 字符串作为新数组中的最后一个元素)。

如果您想专门将数字转换为整数和浮点数,也许有更优雅的方法,但这会起作用(如果您有多余的逗号,它也会删除空单元格):

new_data = []
for i in data:
    strings = i.split(',')
    for s in strings:
        if (len(s)>0):
            try:
                num = int(s)
            except ValueError:
                try:
                    num = float(s)
                except ValueError:
                    num = s
            new_data.append(num)
new_data

【讨论】:

  • 谢谢你的帮助,但我得到了这个 '50' 'bird' 'corn' '105.4' '75' 'cat' 'meat' '10.3,' '100' 'dog' 'eggs ''1000.5'
  • 你的意思是要把字符串中的数字转换成数字?
【解决方案3】:

拆分每个字符串(这会为您提供每个字符串中“,”之间的段数组):

str.split(",")

将数组加在一起

【讨论】:

    【解决方案4】:

    因为列表中的每个字符串都有一个尾随逗号,您可以简单地将它作为一个字符串重新组合在一起,然后用逗号再次拆分。为了在结果列表中获取实际的数字项,您可以这样做:

    import re
    data = [
        "50,bird,corn,105.4,"
        "75,cat,meat,10.3,"
        "100,dog,eggs,1000.5,"
    ]
    numeric = re.compile("-?\d+[\.]\d*$")
    data = [ eval(s) if numeric.match(s) else s for s in "".join(data).split(",")][:-1]
    
    data # [50, 'bird', 'corn', 105.4, 75, 'cat', 'meat', 10.3, 100, 'dog', 'eggs', 1000.5]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-07
      • 2019-02-12
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 1970-01-01
      • 2022-01-06
      相关资源
      最近更新 更多