从卡片列表中-返回具有相同编号的卡片的嵌套列表,然后将其余列表放到单独的列表中。
EXAMPLE: ['6C', '7C', '7D', '8S', '6D']
返回[['7C', '7D'], ['6C','6D'], ['8S']]
我尝试使用while循环,但无法弄清楚。
谢谢!
答案 0 :(得分:1)
这里。试试这个。
from itertools import groupby
a = ['6C', '7C', '7D', '8S', '6D']
a.sort()
final_list = []
for i, j in groupby(a, key=lambda x:x[0]):
final_list.append(list(j))
print(final_list)
答案 1 :(得分:1)
一种可能的解决方案是对列表进行排序,然后使用itertools.groupby对列表进行分组,既使用字符串的整数部分,然后将具有常见整数元素的项目分组在一起
from itertools import groupby
li = ['6C', '7C', '7D', '8S', '6D']
#Sort the list based on the integer part of the string
li = sorted(li, key=lambda x:int(x[0]))
#Group the list based on the integer part of the string
res = [list(group) for _, group in groupby(li, key=lambda x:int(x[0]))]
print(res)
输出将为
[['6C', '6D'], ['7C', '7D'], ['8S']]
答案 2 :(得分:0)
我知道这不是最佳解决方案,但是...
a = ['6C', '7C', '7D', '8S', '6D']
item = []
ls = []
for i in range(len(a)):
if a[i][0] in ls:
continue
else:
ls.append(a[i][0])
temp = []
temp.append(a[i])
for j in range((i+1), len(a)):
if a[i][0] == a[j][0]:
temp.append(a[j])
else:
continue
item.append(temp)
print(item)
答案 3 :(得分:0)
另一种不使用itertools groupby的方法。
l = ['6C', '7C', '7D', '8S', '6D']
result, temp = [], []
l = sorted(l, key=lambda x: x[0])
counter = l[0][0]
for i in l:
if i[0] == counter:
temp.append(i)
else:
result.append(temp)
temp = [i]
counter = i[0]
if temp:
result.append(temp)
print(result)