Python 使用以下条件对字符串进行排序
字符串s1仅包含字母数字字符。我必须按以下条件对字符串进行排序: ->所有排序的小写字母都在大写字母之前 ->所有排序的大写字母都在数字之前 ->所有排序的奇数都在排序的偶数之前 例如,排序1234->ginortS1324 代码:Python 使用以下条件对字符串进行排序,python,Python,字符串s1仅包含字母数字字符。我必须按以下条件对字符串进行排序: ->所有排序的小写字母都在大写字母之前 ->所有排序的大写字母都在数字之前 ->所有排序的奇数都在排序的偶数之前 例如,排序1234->ginortS1324 代码: l、u、o、e=[]、[]、[]、[]、[] 对于排序中的i(输入()): 如果i.isalpha(): 如果i.isupper()或l,则x=u 其他: 如果int(i)%2,则x=o,否则e x、 附加(i) 打印(“.”连接(l+u+o+e)) 有人能帮助理
l、u、o、e=[]、[]、[]、[]、[]
对于排序中的i(输入()):
如果i.isalpha():
如果i.isupper()或l,则x=u
其他:
如果int(i)%2,则x=o,否则e
x、 附加(i)
打印(“.”连接(l+u+o+e))
有人能帮助理解这个代码吗
有什么更简单的方法可以实现吗
def key_function(character):
return (character.isdigit() - character.islower(), character in "02468", character)
input_string = "Sorting1234"
print(*sorted(input_string, key=key_function), sep="")
一艘班轮:
print(
*sorted(input_string, key=lambda x: (x.isdigit() - x.islower(), x in "02468", x)),
sep=""
)
输出:
ginortS1324
我已经解释了下面的每个步骤。在代码编辑器中打开它。这将使它更容易阅读。
l,u,o,e=[],[],[],[] #define lower, upper, odd and even number lists.
for i in sorted(input()): #split the characters so string looks like [s,t,r,i,n,g]
if i.isalpha(): #check if i is a letter
x = u if i.isupper() else l #add x to upper list if it is an upper, if not, add it to l or the lower list. You can see `ternary operator` for more info.
else: #if it is not a letter
x = o if int(i)%2 else e # if the integer is even add it to e, if it is odd, add it to odd.
x.append(i)
print("".join(l+u+o+e)) #join all the sorted letters in their respective order.
这段代码似乎是实现这一点的一种非常简单的方法。它在开头为小写(
l
)、大写(u
)、奇数(o
)和偶数(e
)字符创建4个列表。然后遍历用户提供的字符串
这些都是相同的事情:
string = input()
for character in string:
...
及
他们将排序(input())
放在那里,以确保数字和字符按字母顺序排序
然后,他们检查当前字符是否是字母(.isalpha()
),如果是,则检查字母是大写还是小写(i.isupper()
)
如果字符是数字,他们将检查它是否为偶数(i%2
)。%
称为模,并给出除法的余数。所以如果一个偶数除以2,余数是0(假),如果它是奇数,它是1(真)
基于此,他们正在将必须添加此字符的列表(l、u、o或e
)设置为x
最后,他们将字符附加到特定列表中,并将所有元素添加到一起
for character in input():
...