简体   繁体   English

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

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

Input: 输入:

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

Expected output: 预期产量:

data = ['A', 'B', 'C'], [1, 'ddd', 'eee', 10], [2, 'fff', 'ggg', 20]]
  • Convert columns with numerical values from strings to integers (with quotes around the numbers removed 将具有数字值的列从字符串转换为整数(删除数字周围的引号

I have attempted with the below code but I am getting this error: 我尝试使用以下代码,但我收到此错误:

ValueError: could not convert string to float: A ValueError:无法将字符串转换为float:A

Could anyone point out my mistake? 有谁可以指出我的错误?

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

The 'pythonic' way to do this is to try converting each element to an integer, and fall back to keeping the string in case of failure. '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

What about this: 那这个呢:

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

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

Your variable i , an integer, will never be equal to [1,2], a list. 你的变量i ,一个整数,永远不会等于[1,2],一个列表。 What you meant to say/write is: 你想说/写的意思是:

if i not in [1,2]:

Edit: I forgot the first row. 编辑:我忘记了第一行。 Since your first row is not like the others, either handle it differently (not recommended), or use one of the other answers (recommended) 由于您的第一行与其他行不同,因此要么以不同方式处理(不推荐),要么使用其他答案之一(推荐)

You can apply a lambda function with a condition using map: 您可以使用map应用具有条件的lambda函数:

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

map applies the lambda function on every subelement of d. map将d函数应用于d的每个子元素。 If the element is a string representing a digit, it applies conversion using float , if it is not, it leaves the whole string as it is. 如果元素是表示数字的字符串,则使用float应用转换,如果不是,则保留整个字符串。 It directly replaces the sublist in data. 它直接替换数据中的子列表。

In Python 3.X the result of map would need to be explicitly converted to a list, ie data[i] = list(map()) . 在Python 3.X中,map的结果需要显式转换为列表,即data[i] = list(map())

You can try by using json and regex as follows: 您可以尝试使用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)

Output: 输出:

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

You also mentioned you wanted to remove commas after each list, well here is one way: 您还提到要在每个列表后删除逗号,这里有一种方法:

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

Output: 输出:

['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