如何格式化元素的最后一个字符
> Apple0 = 2, Apple1 = 3, Apple2 = 8, Mango = 10, Banana = 15, Grape0 = 11,
> Grape1 = 20 Potato = 5
到
Apple[0] = 2, Apple[1] = 3, Apple[2] = 8, Mango = 10, Banana = 15, Grape[0] = 11, Grape[1] = 20, Potato = 5
我在网上使用pandas
找到了一些示例,但是很遗憾,我无法将panda
插件安装到我的pycharm
答案 0 :(得分:0)
尝试一下:
from collections import defaultdict
loaded_items = {
'Apple0': 2,
'Apple1': 3,
'Apple2': 8,
'Mango':10,
'Banana': 15,
'Grape0': 11,
'Grape1': 20,
'Potato': 5
}
items = defaultdict(dict)
for k, v in loaded_items.items():
key_letter = ''.join(filter(str.isalpha, k))
items[key_letter][len(items[key_letter]) + 1] = v
print(items)
答案 1 :(得分:0)
尝试一下:
import re
import pprint
loaded_items = {
'Apple0': 2,
'Apple1': 3,
'Apple2': 8,
'Mango':10,
'Banana': 15,
'Grape0': 11,
'Grape1': 20,
'Potato': 5
}
d = {}
for key, val in loaded_items.items():
match = re.search(r'\d+$', key)
if match:
endchar = match.group()
key = key.rstrip(endchar)
d.setdefault(key, [])
d[key].append(val)
else:
d[key] = val
pprint.pprint(d)
{'Apple': [8, 2, 3], 'Banana': 15, 'Grape': [11, 20], 'Mango': 10, 'Potato': 5}
答案 2 :(得分:0)
您似乎具有以下形式
的文件Apple0 = 2, Apple1 = 3, Apple2 = 8, Mango = 10, Banana = 15, Grape0 = 11,
Grape1 = 20 Potato = 5
您要将其重新格式化为
Apple[0] = 2, Apple[1] = 3, Apple[2] = 8, Mango = 10, Banana = 15, Grape[0] = 11,
Grape[1] = 20 Potato = 5
简单:
import re
token_regex = r'([A-Za-z]+)(\d+)'
replacement_regex = r'\1[\2]'
updated_string = re.sub(
token_regex,
replacement_regex,
file.read()
)
print updated_string
输出:
Apple[0] = 2, Apple[1] = 3, Apple[2] = 8, Mango = 10, Banana = 15, Grape[0] = 11,
Grape[1] = 20 Potato = 5