如何将列表/字典的每个项/键中的所有字符索引为唯一ID

2024-09-27 02:25:55 发布

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

我想知道是否有更有效的方法来引用列表/字典中每个项/键的每个索引。Here's a bigger sample dictionary.

raw_dict = {'atgc': 1, 't': 0, 'gcccctttc': 1, 'cttc': 1}
sorted_list = sorted(list(raw_dict))
translation = dict()
i_all = 0
for i_list, item in enumerate(sorted_list):
    for i_item in range(len(item)):
        translation[i_all] = ([i_list, i_item])
        i_all += 1

print sorted_list
# output ['atgc', 'cttc', 'gcccctttc', 't']

print translation
# output {0: [0, 0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [1, 0], 5: [1, 1], 6: [1, 2], 7: [1, 3], 8: [2, 0], 9: [2, 1], 10: [2, 2], 11: [2, 3], 12: [2, 4], 13: [2, 5], 14: [2, 6], 15: [2, 7], 16: [2, 8], 17: [3, 0]}

索引'i\u all'类似于假设的字符串'atgccttcgcctttct',连接排序后的'raw\u dict'键

我想使用所有字符的索引来生成具有可变长度的子字符串,并为“raw\ u dict”中的键创建可变开始索引。但是,我实际上不能将所有键作为一个字符串连接起来,因为这样可能会生成不存在的子字符串。你知道吗


Tags: 字符串inforoutputrawallitemtranslation
1条回答
网友
1楼 · 发布于 2024-09-27 02:25:55

我不确定您想做什么(例如,奇怪的是,您从未实际使用初始字典的),但下面是如何使用list comprehensions生成类似的列表:

# Replace .keys() with .iterkeys() if using Python 2
>>> r = [(i, j) for i, k in enumerate(sorted(raw_dict.keys())) for j in range(len(k))]
>>> print(r)
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (3, 0)]

如果您真的想得到一个dict,如您的示例所示,那么:

>>> s = {i: v for i, v in enumerate(r)}
>>> print(s)
0: (0, 0), 1: (0, 1), 2: (0, 2), 3: (0, 3), 4: (1, 0), 5: (1, 1), 6: (1, 2), 7: (1, 3), 8: (2, 0), 9: (2, 1), 10: (2, 2), 11: (2, 3), 12: (2, 4), 13: (2, 5), 14: (2, 6), 15: (2, 7), 16: (2, 8), 17: (3, 0)}

(我在这里用了dict comprehension。)

相关问题 更多 >

    热门问题