1 回答
TA贡献1818条经验 获得超3个赞
我的解决方案
def convert_data_list(data_list):
data_list = [s.translate({ord(c): None for c in '\'\"'}) for s in data_list]
result = []
for data in data_list:
pairs = []
for int_text_string in data.split(','):
integer, text = [d for d in int_text_string.split('$') if d.strip() != '']
text = text.lstrip('b')
pairs.append('{' + integer + ', ' + text + '}')
result.append('{' + ', '.join(pairs) + '}')
return result
示例使用
my_data_list = [
'1.7.45.67.3',
'\'$10$This is the first team in the league\', "$12$b\'This team is at location 132.45.67 on the grid\'"',
'\'$114$Sample data\', "$78$b\'Hello world\'", "$48$b\'A third pair\'"',
]
my_final_result = convert_data_list(my_data_list[1:]) # do not include zeroth index
my_final_result = [my_data_list[0]] + my_final_result # add zeroth index back
print(result)
输出
['1.7.45.67.3', '{{10, This is the first team in the league}, {12, This team is at location 132.45.67 on the grid}}', '{{114, Sample data}, {78, Hello world}, {48, A third pair}}']
解释
此函数接受字符串列表。仅在第一个索引之后传入字符串。
def convert_data_list(data_list):
1.删除所有单引号和双引号
data_list = [s.translate({ord(c): None for c in '\'\"'}) for s in data_list]
所以这个示例字符串
'\'$10$This is the first team in the league\', "$12$b\'This team is at location 132.45.67 on the grid\'"'
变成
'$10$This is the first team in the league, $12$bThis team is at location 132.45.67 on the grid'
在python中还有其他方法可以做到这一点
2.遍历每个字符串
result = []
for data in data_list:
临时结果存储在result
3. 用逗号分割每个字符串,然后循环遍历每个字符串
pairs = []
for int_text_string in data.split(','):
从第 1 步开始,
'$10$This is the first team in the league, $12$bThis team is at location 132.45.67 on the grid'
变成一个字符串列表
['$10$This is the first team in the league', ' $12$bThis team is at location 132.45.67 on the grid']
4.提取整数和文本值
integer, text = [d for d in int_text_string.split('$') if d.strip() != '']
给定' $12$bThis team is at location 132.45.67 on the grid',拆分'$'给出:
[' ', '12', 'bThis team is at location 132.45.67 on the grid']
由于可能存在仅包含空格的字符串,因此请勿将其包含在列表中以给出最终结果:
['12', 'bThis team is at location 132.45.67 on the grid']
所以 0-index 是整数,1-index 是文本。然后将其分配给变量integer并text通过列表解包。
5.从左边删除第一个字符'b'
text = text.lstrip('b')
如果字符串不以 a 开头,这将不起作用'b'
6. 格式化结果
pairs.append('{' + integer + ', ' + text + '}')
result.append('{' + ', '.join(pairs) + '}')
return result
我不能说这是多么有效,但它确实有效。
添加回答
举报