繁体   English   中英

Python 2.7:使用for循环在列表中格式化列表

[英]Python 2.7: Format a list within a list using for loops

输入:

data = [['A', 'B', 'C'], ['001', 'ddd', 'eee', '10'], ['002', 'fff', 'ggg', '20']]

预期产量:

data = ['A', 'B', 'C'], [1, 'ddd', 'eee', 10], [2, 'fff', 'ggg', 20]]
  • 将具有数字值的列从字符串转换为整数(删除数字周围的引号

我尝试使用以下代码,但我收到此错误:

ValueError:无法将字符串转换为float:A

有谁可以指出我的错误?

formatted = []
for row in data:
    new_row = []
    for i, col in enumerate(row):
        if i != [1,2]:
            new_row.append(col)
            new_row.append(float(col))
    formatted.append(new_row)

print formatted

'pythonic'这样做的方法是尝试将每个元素转换为整数,然后回退到保持字符串失败的情况下。

formatted = []
for row in data:
    new_row = []
    for elem in row:
        try:
            new_row.append(int(elem))
        except ValueError:
            new_row.append(elem)
    formatted.append(new_row)

print formatted

那这个呢:

def to_float(s):
    try:
        return float(s)
    except:
        return s

[[to_float(s) for s in row] for row in data]

你的变量i ,一个整数,永远不会等于[1,2],一个列表。 你想说/写的意思是:

if i not in [1,2]:

编辑:我忘记了第一行。 由于您的第一行与其他行不同,因此要么以不同方式处理(不推荐),要么使用其他答案之一(推荐)

您可以使用map应用具有条件的lambda函数:

for i,d in enumerate(data):
    data[i] = map(lambda x: float(x) if x.isdigit() else x, d)

map将d函数应用于d的每个子元素。 如果元素是表示数字的字符串,则使用float应用转换,如果不是,则保留整个字符串。 它直接替换数据中的子列表。

在Python 3.X中,map的结果需要显式转换为列表,即data[i] = list(map())

您可以尝试使用json和regex,如下所示:

import json, re

data = [['A', 'B', 'C'], ['001', 'ddd', 'eee', '10'], ['002', 'fff', 'ggg', '20']]
data = json.dumps(data)
data = json.loads(re.sub(r'"0*(\d+)"', r'\1', data)

print (data)

输出:

[['A', 'B', 'C'], [1, 'ddd', 'eee', 10], [2, 'fff', 'ggg', 20]]

您还提到要在每个列表后删除逗号,这里有一种方法:

data = reduce(lambda oldList, newList: oldList + newList, data, [])

输出:

['A', 'B', 'C', 1, 'ddd', 'eee', 10, 2, 'fff', 'ggg', 20]

暂无
暂无

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

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