Python 从列表中返回唯一单词(不区分大小写)
我需要帮助,从一个列表中返回不重复的单词(不区分大小写),并保持它们的顺序。
比如说:
def case_insensitive_unique_list(["We", "are", "one", "we", "are", "the", "world", "we", "are", "THE", "UNIVERSE"])
会返回: ["We", "are", "one", "the", "world", "UNIVERSE"]
到目前为止,我的代码是这样的:
def case_insensitive_unique_list(list_string):
uppercase = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
lowercase = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
temp_unique_list = []
for i in list_string:
if i not in list_string:
temp_unique_list.append(i)
我在比较临时唯一单词列表中的每个单词时遇到了麻烦,想知道这个单词是否重复了。例如:“to”和“To”(我觉得使用range函数会有帮助)。
而且为了让它返回原始列表中最先出现的单词,这个函数会用到。
我该如何使用for循环来实现这个呢?
7 个回答
1
l=["We", "are", "one", "we", "are", "the", "world", "we", "are", "THE", "UNIVERSE"]
so=[]
for w in l:
if w.lower() not in so:
so.append(w.lower())
In [14]: so
Out[14]: ['we', 'are', 'one', 'the', 'world', 'universe']
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
1
你可以使用集合来确保每个元素都是独一无二的。当你试图把一个重复的元素添加到集合中时,如果这个元素已经存在,集合会自动把它丢掉。
你还应该使用内置的lower()函数来处理大小写不敏感的问题,也就是说,不管是大写还是小写,都会被当作相同的内容。
uniques = set()
for word in words:
set.add(word.lower()) #lower it first and then add it
如果这是一个作业任务,而使用集合是不允许的,那么你可以很容易地改成只使用列表,只需循环遍历并添加条件即可:
uniques = list()
if word.lower() not in uniques:
#etc
1
你可以这样做:
l = ["We", "are", "one", "we", "are", "the", "world", "we", "are", "THE", "UNIVERSE"]
a = []
for i in l:
if i.lower() not in [j.lower() for j in a]:
a.append(i)
>>> print a
['We', 'are', 'one', 'the', 'world', 'UNIVERSE']
3
你可以使用 set()
和列表推导式来实现:
>>> seen = set()
>>> lst = ["We", "are", "one", "we", "are", "the", "world", "we", "are", "THE", "UNIVERSE"]
>>> [x for x in lst if x.lower() not in seen and not seen.add(x.lower())]
['We', 'are', 'one', 'the', 'world', 'UNIVERSE']
10
你可以通过使用一个 for
循环和 set
数据结构来实现这个功能,像这样:
def case_insensitive_unique_list(data):
seen, result = set(), []
for item in data:
if item.lower() not in seen:
seen.add(item.lower())
result.append(item)
return result
输出结果
['We', 'are', 'one', 'the', 'world', 'UNIVERSE']