[英]2d array if the elements are same
I have list of lists looks like我有列表列表看起来像
a=[[1,2],[2,1],[2,3]]
I would like to check if the fırst elements of sublist are same, if they are same I would like to put them a new list.我想检查子列表的第一个元素是否相同,如果它们相同,我想把它们放在一个新列表中。
I tried我试过
for x in a:
for y in x:
if y in x:
I could not find what to write after that.在那之后我找不到写什么了。 My output is that new lists like我的输出是像这样的新列表
a1=[[2,3,1],[1,2]]
Thank you谢谢
I'll go for dictionary.我去查字典。
a = [[1,2],[2,1],[2,3]]
d = {}
for x in a:
head = x[0]
if head in d.keys():
d[head].extend(x[1:])
else:
d[head] = x[1:]
result = [[key] + d[key] for key in d.keys()]
Try this:尝试这个:
a=[[2,2],[2,1],[2,3]]
myList=[x[0] for x in a]
print(all(y==myList[0] for y in myList))
If same then True else False如果相同则为真否则为假
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.