【问题标题】:Pad each element of the list with the following 0s用以下 0 填充列表的每个元素
【发布时间】:2021-11-10 20:53:19
【问题描述】:

我有一个列表列表:

0      [[[20.5973832, 52.8685205], [20.5974081, 52.86...
1      [[[21.0072715, 52.2413049], [21.0072603, 52.24...
2      [[[18.8446673, 50.4508418], [18.8447041, 50.45...
3      [[[18.8649393, 50.4483321], [18.8649802, 50.44...
4      [[[16.7529018, 53.1424612], [16.7528965, 53..

我需要遍历列表的每个元素(每个坐标号),并确保它在句点后有 7 位数字。如果没有,我需要在末尾用 0 填充,使其在句点后有 7 位数字。

每个数字都是一个浮点数,但我可以将其转换为字符串以使用 len() 函数。

我的代码是:

for a in list_of_lists:
    for b in a:
        for c in b:
            for d in c:
                if(len(str(d))<10):
                    d = str(d).ljust(10-len(str(d)), '0')

我得到的错误是:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-46-70d9d844f41b> in <module>
      3 for a in list_of_lists:
      4     for b in a:
----> 5         for c in b:
      6             for d in c:
      7                 if(len(str(d))<10):

TypeError: 'float' object is not iterable

实现这一目标的更好方法是什么?

【问题讨论】:

标签: python python-3.x iteration nested-lists


【解决方案1】:

recursive_tran 是一个递归辅助函数,用于访问列表中的每个值,这些值可能会替换或修改值。 (信用Python: Replace values in nested dictionary

解决方案

我可以看到的 3 个选项(您可以通过更改 method 参数来运行它们):

  1. 自定义复制

它根本不会改变任何东西,我们只是创建新的浮点类并用字符串格式化程序覆盖 repr 函数。这个非常好,因为它的格式没有字符串撇号,并且值本身根本没有改变。 我建议这个解决方案

  1. 字符串替换

它与 1) 几乎相同,但不同之处在于我们用格式化字符串替换了真正的浮点数,所以你失去了价值,但你得到了你想要的。另一个缺点是字符串有撇号

  1. 四舍五入

真正的交易,但没有你想要的那么好。它将数字四舍五入到小数点后 7 位,但问题是,如果您有一些像 5.0 这样的数字,它不会给您想要的所有小数 (5.0000000),因为没有真正指向它。

结果见下文

def recursive_tran(l: list, depth: int = 0, method: str = "round") -> list:

    x = []
    for e in l:
        if isinstance(e, list):
            e = recursive_tran(e, depth=depth + 1, method=method)
        if isinstance(e, float) or isinstance(e, int):
            if method == "round":
                e = round(e, 7)
            if method == "format":
                e = format(e, ".7f")
            if method == "custom_repr":
                e = FakeRepresentationFloat(round(e, 7))

        x.append(e)
    return x


class FakeRepresentationFloat(float):
    def __repr__(self):
        return format(self, ".7f")
    

x = [[[1.0158, 5.7000155587, [[1, 2.000000000000000008]]]]]

print("Custom repr")
print(recursive_tran(x, method="custom_repr"))
print("String substitution")
print(recursive_tran(x, method="format"))
print("Rounding")
print(recursive_tran(x, method="round"))

>>> Custom repr
>>> [[[1.0158000, 5.7000156, [[1.0000000, 2.0000000]]]]]
>>> String substitution
>>> [[['1.0158000', '5.7000156', [['1.0000000', '2.0000000']]]]]
>>> Rounding
>>> [[[1.0158, 5.7000156, [[1, 2.0]]]]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-16
    • 2020-12-04
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    相关资源
    最近更新 更多