Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python列表基于文本获取唯一元素_Python_Python 3.x - Fatal编程技术网

Python列表基于文本获取唯一元素

Python列表基于文本获取唯一元素,python,python-3.x,Python,Python 3.x,我有一个非常糟糕的未格式化列表[“Foo”,“Foo”,“Bar”] 我想要的是列表中基于文本的唯一元素 input_list = ["'Foo'", 'Foo', 'Bar'] Output list = ['Foo', 'Bar'] >>> ls = ["'Foo'", 'Foo', 'Bar'] >>> ls = list(set(ls)) >>> ls ['Foo', 'Bar', &qu

我有一个非常糟糕的未格式化列表[“Foo”,“Foo”,“Bar”]

我想要的是列表中基于文本的唯一元素

input_list = ["'Foo'", 'Foo', 'Bar']

Output list = ['Foo', 'Bar']


>>> ls = ["'Foo'", 'Foo', 'Bar']
>>> ls = list(set(ls))
>>> ls
['Foo', 'Bar', "'Foo'"]
>>> 
与@的答案类似,但用于维持秩序

代码:

导入字符串
从集合导入订单
def清洁(项目):
返回“”。join(如果char为string.ascii_字母,则项目中的char为char)
ls=[“'Foo'”、'Foo'、'Bar']
ls=列表(OrderedDict.fromkeys(ls中项目的清除(项目))
打印(ls)

基于文本”是什么意思?从元素中删除标点符号?是的,我们可以说删除标点符号或任何其他符号您的代码是正确的,除了第一个“Foo”上有两组引号。是的,但问题是标点符号的“任何其他符号”仍然是不明确的。这也包括ASCII字母。至少我猜你想保留它们:)回答得好,但没有保留正确的答案order@AbhigyanJaiswalOP没有指定他们要保留顺序。他们自己试图用
set
来解决这个问题。是的,但请查看预期输出3.7+无需使用
OrderedDict
,常规
dict
将保留插入顺序。@buran如果版本小于3.7,请直接输入
import string

def clean(item):
    return ''.join(char for char in item if char in string.ascii_letters)

ls = ["'Foo'", 'Foo', 'Bar']
ls = list(set(clean(item) for item in ls))
print(ls)