I have a list of integer like so:
print(list) =
[3584, 71943, 74593, 78252, 79205, 85318, 86152, 92030, 93207, 96977, 100464, 102041]
This is a list of ranges of index values so I want to replace every odd occurrence of comma with a colon like so:
[3584: 71943, 74593: 78252, 79205: 85318, 86152: 92030, 93207: 96977, 100464: 102041]
I have tried several regex examples such as:
re.sub(r'(\b\d{1,2}),',r'\g<1>:',result)
but I keep getting: TypeError: expected string or bytes-like object
I have also tried converting this list to a string then performing the regex solution above but it still did not work.
Any help would be greatly appreciated!
CodePudding user response:
You don't need Regex for that. You already have Python code, so just use Python code to convert the list into a dictionary.
numbers = [3584, 71943, 74593, 78252, 79205, 85318, 86152, 92030, 93207, 96977, 100464, 102041]
dictionary = {}
for i in range(0, len(numbers) - 1, 2):
dictionary[numbers[i]] = numbers[i 1]
print(dictionary)
Result:
{3584: 71943, 74593: 78252, 79205: 85318, 86152: 92030, 93207: 96977, 100464: 102041}
Note:
- don't use the name
list
, because it shadows the Python typelist
CodePudding user response:
Assuming you want string outputs, and not a dictionary or something similar:
ls = [3584, 71943, 74593, 78252, 79205, 85318, 86152, 92030, 93207, 96977, 100464, 102041]
paired = [f"{ls[i]}: {ls[i 1]}" for i in range(0, len(ls), 2)]
As noted, your input is a list of ints, and your desired output is invalid in Python. So this is a guess as to what you want - the other reasonable guess would be a dictionary of key-value pairs mapping from int to int.
ls = [3584, 71943, 74593, 78252, 79205, 85318, 86152, 92030, 93207, 96977, 100464, 102041]
paired = {ls[i]: ls[i 1] for i in range(0, len(ls), 2)}
Essentially, the colon in Python has semantic meaning in certain places. In a dictionary, for instance, in the second solution above, it defines a relationship between a key and a value. It does not have semantic meaning and is therefor an error inside a list - unless it's encapsulated in a string, in which case it's just another character.
CodePudding user response:
Your output is suit for dictionary type. You could use dictionary comprehension with zip
function to slice the list from index 0 with 2 step (even) and from index 1 with 2 step (odd) as key and value pairs.
lst = [3584, 71943, 74593, 78252, 79205, 85318, 86152, 92030, 93207, 96977, 100464, 102041]
dct = {k: v for k, v in zip(lst[0::2], lst[1::2])}
print(dct)
# {3584: 71943, 74593: 78252, 79205: 85318, 86152: 92030, 93207: 96977, 100464: 102041}