Python 为什么列表的代码对于大条目失败?

Python 为什么列表的代码对于大条目失败?,python,Python,我正在为密码编写一个代码,我想将一位数转换为两位数,前面是0 我想翻一张这样的清单: [":","2",":","3",":","4",":"] 为此: [":", "0","2", ":", "0","3". ":", "0","4",":"] 但是我不明白为什么当列表变大时我的代码会失败。 这是我的密码: text = str(input("Enter the text you want to encode: ")) text = ':' + text + ':' n = len(te

我正在为密码编写一个代码,我想将一位数转换为两位数,前面是0

我想翻一张这样的清单:

[":","2",":","3",":","4",":"]
为此:

[":", "0","2", ":", "0","3". ":", "0","4",":"]
但是我不明白为什么当列表变大时我的代码会失败。 这是我的密码:

text = str(input("Enter the text you want to encode: "))
text = ':' + text + ':'

n = len(text)
text = list(text)
t_test = text

for i in range(2,n):
    if text[i] == ':' and text[i-2] == ":":
        t_test.insert((i-1),"0")
t_test = text
print(text)
例如,当我输入以下内容时:

1:2:3:4:5:6
它无法在5和6前面插入零。它的输出是:

[':', '0', '1', ':', '0', '2', ':', '0', '3', ':', '0', '4', ':', '5', ':', '6', ':']
而不是:

[':', '0', '1', ':', '0', '2', ':', '0', '3', ':', '0', '4', ':', '0', '5', ':', '0', '6', ':']

我尝试过使用较小的条目,但我不知道为什么会在某个时候失败。

如果要修改字符串,最好还是使用字符串函数。例如,可以使用正则表达式查找单个数字并添加前导零:

import re

text = '2:3:4:5:6:10:44'

t_test = re.sub(r'\b(\d)\b', r'0\1', ':' + text + ':')
print(t_test, list(t_test), sep="\n")
输出:

:02:03:04:05:06:10:44:
[':', '0', '2', ':', '0', '3', ':', '0', '4', ':', '0', '5', ':', '0', '6', ':', '1', '0', ':', '4', '4', ':']
[':', '0', '2', ':', '0', '3', ':', '0', '4', ':']
[':', '0', '2', ':', '0', '3', ':', '0', '4', ':']

另一种方法,以防您不想使用正则表达式。这里我们(基本上)只使用
str
类和列表理解的方法

text = '1:2:3:4:5:6'
list_ = text.split(':')
format_number = lambda x: f'0{x}' if x.isdigit() and len(x) == 1 else x
result = [* ':' + ":".join([format_number(str(x)) for x in list_]) + ':']
打印输出(结果):


首先,你发布的代码不适用于任何条目,无论大小。下面是我如何使用列表理解来转换列表,如您的示例所示:

l = [":","2",":","3",":","4",":"]
l = [a for b in [["0",i] if i.isdigit() else [i] for i in l] for a in b]
print(l)
输出:

:02:03:04:05:06:10:44:
[':', '0', '2', ':', '0', '3', ':', '0', '4', ':', '0', '5', ':', '0', '6', ':', '1', '0', ':', '4', '4', ':']
[':', '0', '2', ':', '0', '3', ':', '0', '4', ':']
[':', '0', '2', ':', '0', '3', ':', '0', '4', ':']

还有一种方法:

l = [":","2",":","3",":","4",":"]
l = ' '.join([f"0 {i}" if i.isdigit() else i for i in l]).split()
print(l)
输出:

:02:03:04:05:06:10:44:
[':', '0', '2', ':', '0', '3', ':', '0', '4', ':', '0', '5', ':', '0', '6', ':', '1', '0', ':', '4', '4', ':']
[':', '0', '2', ':', '0', '3', ':', '0', '4', ':']
[':', '0', '2', ':', '0', '3', ':', '0', '4', ':']

您正在一个范围内循环,该范围指向列表的原始末端。在列表中插入项目时,它会变长,最后的项被推到一个不再在您范围内的索引中。@jasonharper有办法解决它吗?一般规则:不要修改您正在迭代的项。@MarkTolonen但我正在修改另一个变量t_test not test。当您指定
t_test=text
时,您将
t_test
作为对
text
的引用,不是它的副本。
re.sub(r'\b(\d)\b',r'0\1',f':{text}:')
不是更好吗?@AnnZen OP没有指定Python 3,所以他们可能无法访问f字符串