我需要将第一个列表格式化为与第二个列表相同的格式。
print(incorrent_format_list)
['AsKh', '2sAc', '7hQs', ...]
print(correct_format_list)
[['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs'], ...]
我试着:
for h in incorrect_format_list:
split_lines = h.split(", ")
# but the print output is this:
['AsKh']
['2sKh']
['7hQs']
#rather than what i need:
[['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs'], ...]
您可以按如下方式分割字符串:
my_list = ['AsKh', '2sAc', '7hQs']
corrected_list = [[e[:2], e[2:]] for e in my_list]
print(corrected_list)
输出:
[['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs']]
在学习了其他答案中建议的基本for循环方法之后,您还可以通过将函数映射到初始列表中的每个值来在一行中完成此操作
a = ['AsKh', '2sAc', '7hQs']
list(map(lambda i: [i[:2], i[2:]], a))
的想法是通过切片将每个字符串从中间分开。这里用的是2,因为每个条目的长度都是固定的。
如果是整个列表,则用大写字母分割
考虑incorrect_list=['AsKh', '2sAc', '7hQs']
import re
correct_format_list=[]
for i in incorrect_list:
correct_format_list.append(re.split('(?<=.)(?=[A-Z])', i))
print (correct_format_list)
输出:
[['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs']]
您可以使用more_itertools
库对字符串进行切片。然后将这些拆分的字符串列表添加到输出列表(fs)中:
from more_itertools import sliced
ss = ['AsKh', '2sAc', '7hQs']
fs = []
for h in ss:
fs.append(list(sliced(h, 2)))
print(fs)
输出:
[[', ', ' Kh '],[‘2 s’,‘交流’],["7 h"、"Qs"]]