简体   繁体   English

python - 如何使用join方法和sort方法

[英]python - how to use the join method and sort method

My purpose is to get an input as a string and return a list of lower case letters of that string, without repeats, without punctuations, in alphabetical order.我的目的是将输入作为字符串,并按字母顺序返回该字符串的小写字母列表,没有重复,没有标点符号。 For example, the input "happy!"例如,输入“快乐!” would get ['a','h','p','y'].会得到 ['a','h','p','y']。 I try to use the join function to get rid of my punctuations but somehow it doesn't work.我尝试使用 join 函数来摆脱我的标点符号,但不知何故它不起作用。 Does anybody know why?有人知道为什么吗? Also, can sort.() sort alphabets?另外, sort.() 可以对字母排序吗? Am I using it in the right way?我是否以正确的方式使用它? Thanks!谢谢!

def split(a):
    a.lower()
    return [char for char in a]

def f(a):
    i=split(a)
    s=set(i)
    l=list(s)
    v=l.join(u for u in l if u not in ("?", ".", ";", ":", "!"))
    v.sort()
    return v

.join() is a string method, but being used on a list, so the code raises an exception, but join and isn't really needed here. .join()是一个字符串方法,但在列表上使用,因此代码引发异常,但join在这里并不是真正需要的。

You're on the right track with set() .你在正确的轨道上使用set() It only stores unique items, so create a set of your input and compute the intersection(&) with lower case letters.它只存储唯一的项目,因此创建一组输入并用小写字母计算交集(&)。 Sort the result:对结果进行排序:

>>> import string
>>> s = 'Happy!'
>>> sorted(set(s.lower()) & set(string.ascii_lowercase))
['a', 'h', 'p', 'y']

You could use:你可以使用:

def f(a):
    return sorted(set(a.lower().strip('?.;:!')))

>>> f('Happy!')
['a', 'h', 'p', 'y']

You could also use regex for this:您也可以为此使用正则表达式:

pattern = re.compile(r'[^a-z]')

string = 'Hello@ W0rld!!#@'

print(sorted(set(pattern.sub('', string))))

Output:输出:

['d', 'e', 'l', 'o', 'r']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM