首页 > 解决方案 > 生成位置列表 (1, (2, 3), 4, (5, 6)) 如何?

问题描述

您好,我想知道如何为字符串切片的位置列表创建整数/元组列表。与标题相同的示例只是列出这种格式: (1, (2, 3), 4, (5, 6))

# my current attempt: 
str_input, decrypted_str = "tester", ""
num_lists = [[x] + [(x + 1, x + 2)] for x in range(0, len(str_input), 4)]
for clist in num_lists:
    for position in clist:
        if isinstance(position, int):
            decrypted_str += str_input[position]
        else:
            decrypted_str += str_input[position[0]:position[1]+1]
print(decrypted_str)

这导致“测试器”,但输出应该是测试器。

标签: python

解决方案


最后一行之前的行应该是

decrypted_str += str_input[position[0]:position[1]+1]

因为 1:5 表示 1,2,3,4 而不是 5


推荐阅读