[英]How to store the positions of an element in string in a dictionary (Python)?
I want to get all the positions (indexes) of an element in a string and store them in a dictionary.我想获取字符串中元素的所有位置(索引)并将它们存储在字典中。
This is what I've tried:这是我试过的:
string = "This is an example"
test = {letter: pos for pos, letter in enumerate(string)}
But this only gives the last position of the letter.但这只给出了字母的最后一个 position。 I'd like all positions, desired output:
我想要所有职位,需要 output:
test["a"]
{8, 13}
At the moment you are overwriting the dictionary values.目前您正在覆盖字典值。 For example,
例如,
>>> my_dict = {}
>>> my_dict['my_val'] = 1 # creating new value
>>> my_dict
{'my_val': 1}
>>> my_dict['my_val'] = 2 # overwriting the value for `my_val`
>>> my_dict
{'my_val': 2}
If you want to keep all values for a key you can use a list along with dict.setdefault
method.如果你想保留一个键的所有值,你可以使用一个列表和
dict.setdefault
方法。
>>> print(dict.setdefault.__doc__)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
>>>
>>> result = {}
>>> string = "This is an example"
>>>
>>> for index, value in enumerate(string):
... result.setdefault(value, []).append(index)
...
>>> result["a"]
[8, 13]
output = {}
input_string
and assigning it the character "This is an example"
input_string
的 input_string 变量并为其分配字符"This is an example"
input_string = "This is an example"
index
and the characterindex
和字符character
.character
。output.setdefault(character, [])
is checking if the key character
exists in the dictionary output
. output.setdefault(character, [])
正在检查字典output
中是否存在关键character
。 If it does not exist, it will create the key character
and assign it the character []
.character
并为其分配字符[]
。 If it does exist, it will return the character of the key character
.character
。 Then, .append(index)
will append the character of index
to the character of the key character
..append(index)
将 append index
的字符添加到 key character
的字符。for index, character in enumerate(input_string):
output.setdefault(character, []).append(index)
output["i"]
[2, 5]
output = {}
input_string = "This is an example"
for index, character in enumerate(input_string):
output.setdefault(character, []).append(index)
output = {}
input_string = "This is an example"
for index, character in enumerate(input_string):
output.setdefault(character, set()).add(index)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.