【问题标题】:Attempting to build a loop to change one str out of 3 strs in python试图建立一个循环来改变python中3个str中的一个
【发布时间】:2021-10-28 05:44:47
【问题描述】:

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

第一个是输入:从ABCD中选择3来创建AAA,ABC...等
第二个是输出:更改每个输入的中间字母并创建一个新列表。例如:对于 AAA -> ABA、ACA、ADA。所以输入长度的3倍。
第三个是Change:我想把每一个变化都命名为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

但我被困在如何创建输出列表上。任何想法表示赞赏!

谢谢

【问题讨论】:

  • 首先,product 不做“随机”选择。您确定要随机选择,还是要在代码中使用product?这是为了减少大家的困惑。
  • 很抱歉给您带来了困惑。我的意思是我的代码中的“产品”。
  • input 是保留关键字。您应该更改该变量的名称。
  • 你是对的,谢谢
  • 是的。我更想知道如何制作清单 2。谢谢

标签: python


【解决方案1】:

您可以使用列表推导:

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)相同,则替换被丢弃。

【讨论】:

  • 谢谢!这是一种非常有效的方式
  • 如果我想将 lst_input 中的每一个复制 3 次以使其像 ('A','A','A'),('A','A', 'A'),('A','A','A'),('A','A','B')...等等?我试过: lst_input1 = [] for j in range(0,64): lst_input1 = append[lst_input[j:j+1]*3],但不工作。我应该改变什么来做到这一点?谢谢
  • @Geinkehdsk 可能有更有效的方法,但试试lst_input1 = [x for x in lst_input for _ in range(3)]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 2015-08-30
  • 2016-10-17
  • 2015-09-16
  • 1970-01-01
相关资源
最近更新 更多