提问人:pab1994 提问时间:5/21/2023 最后编辑:LeoEpab1994 更新时间:5/22/2023 访问量:72
如何根据特定标准对 Python 中的随机单词进行排序?
How can I sort a random word in Python based on specific criteria?
问:
如何按不同的排序逻辑(标准)对随机单词进行排序?
一本书中的一个练习要求我制作一个程序,根据某些标准对随机单词的字母进行排序。
- 首先,所有小写字母按升序排列,相同但带有大写字母。
- 然后用数字(我想是数字)按奇数和偶数按升序对它们进行排序。
- 最后,创建一个新变量来存储您创建的新单词,该单词按上述所有条件排序。
这本书给了我和例子。
给定“OrDenar1234”这个词,新世界应该是“aenrrDO1324”
需要注意的是,我仍然没有进入 python 书的函数部分。所以我正在尝试用我现在拥有的知识(变量、条件、循环、列表等)来做到这一点。
PD:世界是用输入向用户询问的。
答:
0赞
Osman
5/21/2023
#1
# Take the word as input
word = input("Enter a word: ")
# Separate out the lowercase, uppercase, and digits
lowercase_letters = [char for char in word if char.islower()]
uppercase_letters = [char for char in word if char.isupper()]
digits = [char for char in word if char.isdigit()]
# Sort the lowercase and uppercase letters
lowercase_letters.sort()
uppercase_letters.sort()
# Separate and sort the odd and even digits
odd_digits = [digit for digit in digits if int(digit) % 2 != 0]
even_digits = [digit for digit in digits if int(digit) % 2 == 0]
odd_digits.sort()
even_digits.sort()
# Combine all of them to form the final string
final_word = "".join(lowercase_letters + uppercase_letters + odd_digits + even_digits)
print(final_word)
- 要求用户输入一个单词。
- 将该单词分解为小写字母、大写字母和数字。
- 按升序对每个组进行排序。
- 将排序的组组合在一起,形成最终单词。
- 最后,打印最终结果!!
0赞
Steph
5/21/2023
#2
您可以使用内置的字符串方法:、 和 (我没有使用该方法,因为我使用了子句。str.islower()
str.isupper()
str.isdigit()
str.isdigit()
else
s = 'OrDenar1234'
middle = ''
end = ''
start = ''
for i in sorted(s):
if i.islower():
start += i
elif i.isupper():
middle += i
else:
end += i
print(start + middle + end)
输出:
aenrrDO1234
评论
0赞
slothrop
5/22/2023
OP 希望奇数在偶数之前排序。因此,预期输出是 而不是 。aenrrDO1324
aenrrDO1234
0赞
JustaNobody
5/21/2023
#3
上面的答案是编写这个程序的更好方法。但是,在开始时,这对我来说更容易理解。所以我想我应该把它放在这里。排序
s = "Test1231DEche"
lc="" # lc=[] list for sort() function
uc=""
edigits=""
odigits=""
for i in s: #iterate through string
if(i.islower()):#check lower case
lc+=i
elif(i.isdigit()):
if(int(i)%2==0):
edigits+=i #check even digits
else:
odigits+=i
elif(i.isupper()): #check uppercase
uc+=i
lc=sorted(lc) #sorted since string, for sort() you need to make above to list
uc=sorted(uc) #uc after sort is a list you can see by printing them
edigits=sorted(edigits) #edigits.sort() for list
odigits=sorted(odigits)
print(uc)
fin = ' '.join(lc+uc+edigits+odigits) #join above list to string
print(fin)
评论