如何在保留区分大小写的同时消除Python中的重复列表项? [英] How to eliminate duplicate list entries in Python while preserving case-sensitivity?

查看:257
本文介绍了如何在保留区分大小写的同时消除Python中的重复列表项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种从Python列表中删除重复条目的方法,但要有所改变.最终列表必须区分大小写,并且优先使用大写单词.

I'm looking for a way to remove duplicate entries from a Python list but with a twist; The final list has to be case sensitive with a preference of uppercase words.

例如,在cupCup之间,我只需要保留Cup而不是cup.与建议先使用lower()的其他常见解决方案不同,我更喜欢在这里保留字符串的大小写,尤其是我更喜欢保留带有大写字母的字符串而不是小写的字母..

For example, between cup and Cup I only need to keep Cup and not cup. Unlike other common solutions which suggest using lower() first, I'd prefer to maintain the string's case here and in particular I'd prefer keeping the one with the uppercase letter over the one which is lowercase..

我再次尝试列出此列表: [Hello, hello, world, world, poland, Poland]

Again, I am trying to turn this list: [Hello, hello, world, world, poland, Poland]

对此:

[Hello, world, Poland]

我应该怎么做?

谢谢.

推荐答案

这不会保留words的顺序,但是会生成唯一"单词列表,并且优先使用大写单词.

This does not preserve the order of words, but it does produce a list of "unique" words with a preference for capitalized ones.

In [34]: words = ['Hello', 'hello', 'world', 'world', 'poland', 'Poland', ]

In [35]: wordset = set(words)

In [36]: [item for item in wordset if item.istitle() or item.title() not in wordset]
Out[36]: ['world', 'Poland', 'Hello']

如果您希望保留订单在words中显示的顺序,则可以使用 collections.OrderedDict :

If you wish to preserve the order as they appear in words, then you could use a collections.OrderedDict:

In [43]: wordset = collections.OrderedDict()

In [44]: wordset = collections.OrderedDict.fromkeys(words)

In [46]: [item for item in wordset if item.istitle() or item.title() not in wordset]
Out[46]: ['Hello', 'world', 'Poland']

这篇关于如何在保留区分大小写的同时消除Python中的重复列表项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆