Python函数按字母顺序对每个字符串中的字母进行排序

Python函数按字母顺序对每个字符串中的字母进行排序,python,string,list,sorting,Python,String,List,Sorting,我想写一个函数,它获取字符串列表,对每个字符串中的字母进行排序,然后对完整列表进行排序 a = ['hi' , 'hello', 'at', 'this', 'there', 'from'] def string_fun(a): for i in a: b= sorted(''.join(sorted(i)) for i in a) return(b) string_fun(a) 所以我创建了一个字符串列表“a”。这段代码工作得很好,但是有没有办法拆分b变量的代

我想写一个函数,它获取字符串列表,对每个字符串中的字母进行排序,然后对完整列表进行排序

a = ['hi' , 'hello', 'at', 'this', 'there', 'from']
def string_fun(a):
    for i in a:
        b= sorted(''.join(sorted(i)) for i in a)
    return(b)
string_fun(a)
所以我创建了一个字符串列表“a”。这段代码工作得很好,但是有没有办法拆分b变量的代码?我希望这个函数首先对每个字符串中的字母进行排序,然后对完整列表进行排序

a = ['hi' , 'hello', 'at', 'this', 'there', 'from']
def string_fun(a):
    for i in a:
        b= sorted(''.join(sorted(i)) for i in a)
    return(b)
string_fun(a)
我试着这样做:

a = ['hi' , 'hello', 'at', 'this', 'there', 'from']
def string_fun(a):
    for i in a:
        b=''.join(sorted(i))
        for i in b:
            c= sorted()
                  
    return(c)
string_fun(a)

但是我得到一个错误“排序期望1个参数,得到0”

您误解了python中
循环的
语法。在a
中为x写入
时,变量
x
不是用于获取元素为
a[x]
的索引。变量
x
是元素

所以你可以写:

result=[]
对于a中的x:
result.append(“”.join(排序(x)))
result.sort()
或相当于:

result=[]
对于范围内的i(len(a)):
result.append(“”.join(排序(a[i]))
result.sort()
或等效地,使用列表理解:

result=sorted(“”.join(sorted(x))表示a中的x)
请花些时间阅读更多关于python中循环和列表理解的内容:

  • )

您是否尝试过“a中的i”而不是“a中的i”尝试一下:打印(a中的el的排序(“”.join(排序(el))听起来并不是一个有意义的最终目标。你为什么要那样?