[英]Python list into sublists based on the equality of first digit of the list elements
a = [58,23,12,24,11,63,54]
I want to make the above list as follows:我想将上面的列表制作如下:
[[58,54],[23,24],[12,11]]
ie, I want to make the list of sublists whose elements start with same digit and having count > 1.即,我想制作其元素以相同数字开头且计数 > 1 的子列表列表。
You can use dictionary你可以用字典
from collections import defaultdict
a = [58,23,12,24,11,63,54]
d = defaultdict(list)
for num in a:
d[str(num)[0]].append(num)
res = [v for v in d.values() if len(v) > 1]
print(res)
Output: Output:
[[58, 54], [23, 24], [12, 11]]
This code groups integer of any digit on the basis of the first digit.此代码根据第一位数字对任何数字的 integer 进行分组。 I hope this is what you are looking for.
我希望这就是你要找的。 Also this may not be the most efficient way of doing this.
此外,这可能不是最有效的方法。
a=[58,23,12,24,11,63,54]
final=[[],[],[],[],[],[],[],[],[],[]]
for i in a:
count=0
a=i
while (i>0):
count+=1
i=i//10
final[int(a/(10**(count-1)))].append(a)
a=[]
for i in final:
if len(i)>1:
a.append(i)
print(a)
you can use itertools.groupby
to group a list by any key function you want:您可以使用
itertools.groupby
按您想要的任何键 function 对列表进行分组:
note the use of Python 3.8's "walrus operator"注意使用Python 3.8 的“海象算子”
from itertools import groupby
a=[58,23,12,24,11,63,54]
get_first_digit = lambda n: str(n)[0]
sorted_by_digit = sorted(a, key=get_first_digit, reverse=True) # sorting is a must for groupby
result = [y for _,g in groupby(sorted_by_digit, key=get_first_digit) if len(y:=list(g))>1]
print(result)
Output: Output:
[[58, 54], [23, 24], [12, 11]]
I have an answer to this, although it is very big.我有一个答案,虽然它很大。
a = [58,23,12,24,11,63,54]
s = [[a[0]]]
def firstdigit(n):
while n>=10:
n = n//10
return n
def arrange(s, i):
for j in range(len(s)):
if firstdigit(s[j][0]) == firstdigit(i):
s[j].append(i)
break
else:
m=[]
m.append(i)
s.append(m)
return s
def check(s):
for i in s:
if len(i) <= 1:
s.remove(i)
return s
for i in a[1:]:
s = arrange(s, i)
#checks for count>1
s = check(s)
print(s)
This code contains only basics with no modules imported.此代码仅包含基础知识,没有导入任何模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.