如何解决从python的嵌套列表中提取最后一个项目
我有一些嵌套列表。我想提取每个子列表中最后出现的元素(例如,第一个子列表的“再见”)。然后,我想将所有这些最近发生的元素(“再见”,“再见”,“你好”和“ ciao”)添加到新列表中,以便我可以轻松地对它们进行计数,并找出哪个是最频繁出现的元素( '再见)。
问题是我的代码给我留下了一个空列表。我看过Extracting first and last element from sublists in nested list和How to extract the last item from a list in a list of lists? (Python),它们并不是我想要的。
感谢您的帮助!
my_list = [['hello','bye','bye'],['hello','hello','hello'],'ciao']]
# Make a new list of all of the last elements in the sublists
new_list = []
for sublist in my_list:
for element in sublist:
if sublist.index(element) == -1:
new_list.append(element)
# MY OUTPUT
print(new_list)
[]
# EXPECTED OUTPUT
['bye','ciao']
# I would then use new_list to find out what the most common last element is:
most_common = max(set(new_list),key = new_list.count)
# Expected final output
print(most_common)
# 'bye'
解决方法
您正在寻找这个:
for sublist in my_list:
new_list.append(sublist[-1])
索引-1
不“确实存在”,这是一种告诉python从列表末尾开始计数的方法。这就是为什么在寻找-1
时不会像您一样找到匹配项的原因。
此外,您无需遍历所有列表,这是不必要的,因为您可以通过获取我的代码中看到的最后一项来进行“随机访问”。
使用列表推导,甚至还有更多的Python方式:
new_list = [sublist[-1] for sublist in my_list]
然后,您不需要任何for
循环。
您可以通过调用索引-1来调用列表的最后一个元素,例如sublist[-1]
。以下代码应能为您带来预期的结果:
my_list = [['hello','bye','bye'],['hello','hello','hello'],'ciao']]
new_list = list()
for sublist in my_list:
new_list.append(sublist[-1])
print(new_list)
或者正如Risoko指出的那样,您可以在一行中完成此操作,因此代码应类似于
my_list = [['hello','ciao']]
new_list = [sublist[-1] for sublist in my_list]
print(new_list)
,
output = [sublist[-1] for sublist in my_list]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。