如何在python中修改列表的内容

我有一个包含以下项目的列表:

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\'"']

我希望能够将第一个索引之后的列表内容转换为以下内容。该列表在第一个索引之后可能有几个项目,并且{}每个项目只会多几个。

my_final_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}}']

我真的很困惑如何有效地做到这一点。我对 python 很陌生,如果能有效解决这个问题,我将不胜感激。


FFIVE
浏览 137回答 1
1回答

泛舟湖上清波郎朗

我的解决方案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 indexmy_final_result = [my_data_list[0]] + my_final_result    # add zeroth index backprint(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:临时结果存储在result3. 用逗号分割每个字符串,然后循环遍历每个字符串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我不能说这是多么有效,但它确实有效。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python