在python中,如何在列表中运行数字?

2024-04-20 10:55:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表[X, 9, 2, 1, 8, X, 8, 7, 0, 8, 8, 0, 5, 0, 8, 9]。我希望能够用数字0-9替换每个“X”字符串,并用这些数字生成每个可能组合的列表。你知道吗

我初始化了新的列表,在中附加了旧列表中的项,并使用if语句将“X”替换为新值,但运气不太好。你知道吗

所需的输出是生成每个组合的列表,其中“X”替换为数字0-9。你知道吗

我已经尝试将其转换为字符串,然后使用for循环替换X,如下所示:

unknown = ['X', 9, 2, 1, 8, 'X', 8, 7, 0, 8, 8, 0, 5, 0, 8, 9]
unknown = ''.join(unknown)
for i in range(10):
    known = unknown.replace('X', str(i))
    x = unknown.replace('X', str(i))

但这并没有给我所有可能的组合。你知道吗


Tags: 字符串in列表forifrange数字语句
3条回答

一行就行了。这是Python的力量:

[[x, 9, 2, 1, 8, y, 8, 7, 0, 8, 8, 0, 5, 0, 8, 9] for x in range(10) for y in range(10)]

如果希望两个'X'具有相同的值,则更容易:

[[x, 9, 2, 1, 8, x, 8, 7, 0, 8, 8, 0, 5, 0, 8, 9] for x in range(10)]

itertools使用product

来自itertools进口产品

l = ['X', 9, 2, 1, 8, 'X', 8, 7, 0, 8, 8, 0, 5, 0, 8, 9]
>>> for numPerm in product(range(10), repeat = l.count('X')):
    s = [_ for _ in l]
    for num,index in zip(list(numPerm),[i for i,j in enumerate(l) if j == 'X']):
        s[index] = num
    print(s)

这将适用于任何数量的X,所以你不需要一直要求这样做你的家庭作业

我建议计算要替换多少元素,然后使用itertools.product生成所有组合。你知道吗

replacement_count = lst.count('X')

combinations = itertools.product(range(10), repeat=replacement_count)

for combo in combinations:
    combo = iter(combo)
    new_lst = [next(combo) if ch=='X' else ch for ch in lst]

这是我见过的最难看的一行:

[[next(combo) if ch=='X' else ch for ch in lst] for combo in map(iter, itertools.product(range(10), repeat=lst.count('X')))]

相关问题 更多 >