如何将 list/dictionary 的每个 item/key 中的所有字符索引为唯一 ID

How to index all chars in every item/key for a list/dictionary as unique ids

我想知道是否有更有效的方法来引用 list/dictionary 中每个 item/key 的每个索引。 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_all'类似于一个假设的字符串'atgccttcgcccctttct',加入排序的'raw_dict'键

我想使用所有字符的索引来为 'raw_dict' 中的键创建具有可变长度和可变起始索引的子字符串。但是,我实际上无法将所有键作为字符串连接,因为这可能会生成不存在的子字符串。

我不确定你想做什么(例如,奇怪的是你从来没有真正使用初始字典的 values),但这里是如何产生使用 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。)