Py学习  »  Python

试图构建一个循环来更改python中3个str中的一个str

Geinkehdsk • 3 年前 • 1209 次点击  

我的目标是创建3个列表。

第一个是输入:从ABCD中选择3以创建AAA、ABC。。。等
第二个是输出:更改每个输入的中间字母并创建一个新列表。例如:对于AAA->阿坝,阿坝,阿达。所以是输入长度的3倍。
第三个是变化:我想将每个变化命名为c_I,例如AAA->ABA是C1。

作为输入,

>>> lis = ["A","B","C","D"]
>>> import itertools as it
>>> inp = list(it.product(lis, repeat = 3))
>>> print(inp)
[('A', 'A', 'A'), ('A', 'A', 'B'), ... ('D', 'D', 'C'), ('D', 'D', 'D')]
>>> len(inp)
64

但是我被困在如何创建输出列表上。任何想法都很感激!

谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131196
 
1209 次点击  
文章 [ 1 ]  |  最新文章 3 年前
j1-lee
Reply   •   1 楼
j1-lee    3 年前

你可以使用列表理解:

import itertools

lst = ['A', 'B', 'C', 'D']

lst_input = list(itertools.product(lst, repeat=3))
lst_output = [(tup[0], x, tup[2]) for tup in lst_input for x in lst if tup[1] is not x]
lst_change = [f'C{i}' for i in range(1, len(lst_output) + 1)]

print(len(lst_input), len(lst_output), len(lst_change))
print(lst_input[:5])
print(lst_output[:5])
print(lst_change[:5])

# 64 192 192
# [('A', 'A', 'A'), ('A', 'A', 'B'), ('A', 'A', 'C'), ('A', 'A', 'D'), ('A', 'B', 'A')]
# [('A', 'B', 'A'), ('A', 'C', 'A'), ('A', 'D', 'A'), ('A', 'B', 'B'), ('A', 'C', 'B')]
# ['C1', 'C2', 'C3', 'C4', 'C5']

对于中的每个元组 lst_input ,中间项被所有候选字符替换,但如果替换字符与原始字符相同,则替换将被丢弃( if tup[1] is not x ).