Python 如何显示列表中元音的数量?
首先,我需要编写一个程序,按照行星相对于太阳的位置降序显示列表中行星的名称。 然后,我应该编写一个程序,按照行星名称中元音的数量按升序显示行星列表中行星的名称 我已经能做第一部分了。然而,我无法理解第二部分Python 如何显示列表中元音的数量?,python,Python,首先,我需要编写一个程序,按照行星相对于太阳的位置降序显示列表中行星的名称。 然后,我应该编写一个程序,按照行星名称中元音的数量按升序显示行星列表中行星的名称 我已经能做第一部分了。然而,我无法理解第二部分 Planets = [("Mercury", 75, 1), ("Venus", 460, 2), ("Mars", 140, 4), ("Earth", 510, 3), ("Jupiter", 62000, 5), ("Neptune", 7640, 8),
Planets = [("Mercury", 75, 1), ("Venus", 460, 2), ("Mars", 140, 4),
("Earth", 510, 3), ("Jupiter", 62000, 5), ("Neptune", 7640, 8),
("Saturn", 42700, 6), ("Uranus", 8100, 7)]
def main():
Planets.sort(key=Sort_By_Position,reverse=True)
print("The names of the planets in descending order by their position from the Sun: ")
for i in Planets:
print (i[0])
print(" ")
print("Planets in ascending order by the number of vowels in planet name: ")
Planets.sort(key=vowel_count)
for i in Planets:
print(i[0])
def Sort_By_Position(Planets):
return Planets[-1]
def vowel_count():
main()
我希望这个程序能通过行星名称中元音的数量来显示行星的升序。下面是解决方案
Planets = [("Mercury", 75, 1), ("Venus", 460, 2), ("Mars", 140, 4), ("Earth", 510, 3), ("Jupiter", 62000, 5), ("Neptune", 7640, 8), ("Saturn", 42700, 6), ("Uranus", 8100, 7)]
# decending order in order
new_pl=Planets.copy()
new_pl.sort(key=lambda x:x[2], reverse=True) # sorting on position value
print(new_pl)
"""
output
[('Neptune', 7640, 8), ('Uranus', 8100, 7), ('Saturn', 42700, 6), ('Jupiter', 62000, 5), ('Mars', 140, 4), ('Earth', 510, 3), ('Venus', 460, 2), ('Mercury', 75, 1)]
"""
# in no of vowels present
vowel = ['a','e','i','o','u']
# in vowels
def count(name):
vowel = ['a','e','i','o','u']
val=0
for i in name.lower():
if i in vowel:
val+=1
return val
new_pl_2=Planets.copy()
new_pl_2.sort(key=lambda x:count(x[0])) #sorting on count of vowels
print(new_pl_2)
"""
output
[('Mars', 140, 4), ('Mercury', 75, 1), ('Venus', 460, 2), ('Earth', 510, 3), ('Saturn', 42700, 6), ('Jupiter', 62000, 5), ('Neptune', 7640, 8), ('Uranus', 8100, 7)]
"""
你提到你能做第一部分,所以你基本上只问第二部分。以下示例将帮助您找到正确的方向:
>>> planets = ['Mercury','Venus','Earth','Mars','Neptune','Jupiter','Saturn','Uranus']
>>> vowels = ('a','e','i','o','u')
>>> name_counts = []
>>> for name in planets:
... count = sum([1 for letter in name if letter.lower() in vowels])
... name_counts.append((name,count))
...
>>> print(sorted(name_counts, key=lambda x: x[1]))
[('Mars', 1), ('Mercury', 2), ('Venus', 2), ('Earth', 2), ('Saturn', 2), ('Neptune', 3), ('Jupiter', 3), ('Uranus', 3)]
您可以在一行中使用
elem[0]
包含您正在迭代的行星的名称。当您迭代一个字符串(x in elem[0]
)时,它将迭代该字符串中的每个字符。例如,'Earth'
变成['E','a','r','t','h']
从这里,我们可以简单地过滤列表理解,使其只包含元音(
如果x.lower()在('a','e','i','o','u')
),并返回理解的长度,这将反馈给排序方法。您没有实现一个计算元音的函数,那么为什么希望它按元音排序呢,StackOverflow的存在不是为了帮你做家庭作业。但这并不意味着你不能问关于家庭作业的问题。如果您至少尝试以某种方式实现元音计数,您就更有可能得到有用的答案。e、 g.尝试用谷歌搜索函数,至少搜索一个字符串,然后尝试在列表中迭代。如果这样做不起作用,可以问一些关于你遇到的问题的具体问题,而不是让别人为你提供完整的解决方案。
def vowel_count(elem):
return len([x for x in elem[0] if x in ('a', 'e', 'i', 'o', 'u')])