从python的嵌套列表中提取最后一个项目

问题描述

我有一些嵌套列表。我想提取每个子列表中最后出现的元素(例如,第一个子列表的“再见”)。然后,我想将所有这些最近发生的元素(“再见”,“再见”,“你好”和“ ciao”)添加到新列表中,以便我可以轻松地对它们进行计数,并找出哪个是最频繁出现的元素( '再见)。

问题是我的代码给我留下了一个空列表。我看过Extracting first and last element from sublists in nested listHow 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'

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)