【问题标题】:How to add prefixes and suffixes to permutations in Python? [duplicate]如何在 Python 中为排列添加前缀和后缀? [复制]
【发布时间】:2020-12-21 18:40:41
【问题描述】:

我正在尝试制作一个以 X 为前缀并以 Y 为后缀的排列列表。 以下是我尝试过的一些示例。


perm = permutations ([1,2,3], 3)

for i in list(perm):
    print ("Adam" + (i) + "Bob")

这会带回错误“TypeError: can only concatenate str (not "tuple") to str”


perm = permutations ([1,2,3], 3)

for i in list(perm):
    list (i)
    
def blink():
    print (("X" + (i) + "Y"))

blink()

这会带回错误“TypeError: can only concatenate str (not "tuple") to str”

理想情况下,最终结果会打印出来

X(1, 2, 3)Y
X(1, 3, 2)Y
X(2, 1, 3)Y
X(2, 3, 1)Y
X(3, 1, 2)Y
X(3, 2, 1)Y

【问题讨论】:

  • 旁注:这里没有理由做for i in list(perm):permutations 已经返回了一个迭代器,而list在迭代之前立即对其进行化仅意味着您必须在只需要一个时使用所有tuples 制作一个(可能很昂贵,尽管在这种情况下不是)临时的tuples一次。

标签: python tuples permutation


【解决方案1】:

每个元素都是一个元组,所以先将其转换为带有str的字符串:

for i in perm:
    print("Adam" + str(i) + "Bob")

或者,只使用 f 字符串:

for i in perm:
    print(f"Adam{i}Bob")

【讨论】:

  • Alternative: print("Adam", i, "Bob", sep="")print 无需额外临时变量即可进行格式化(f-string 变体可能更快,并且适用于更多情况,只需注意在 @987654326 的特定情况下@您不需要将其格式化为单个最终字符串)。
猜你喜欢
  • 1970-01-01
  • 2016-12-25
  • 2017-08-26
  • 2015-12-05
  • 2018-11-01
  • 2016-03-07
  • 1970-01-01
相关资源
最近更新 更多