3 回答
TA贡献1802条经验 获得超6个赞
您提到您能够完成第一部分,因此您基本上只询问第二部分。以下示例应该可以帮助您指明正确的方向:
>>> 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)]
TA贡献1757条经验 获得超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)]
# 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)]
"""
TA贡献1846条经验 获得超7个赞
您可以使用列表理解在一行中完成此操作。
def vowel_count(elem): return len([x for x in elem[0] if x in ('a', 'e', 'i', 'o', 'u')])
elem[0]
包含您正在迭代的行星的名称。当您遍历字符串 ( x in elem[0]
) 时,它将遍历该字符串中的每个单独字符。例如,'Earth'
变成['E', 'a', 'r', 't', 'h']
。
从那里,我们可以简单地过滤列表推导式以仅包含元音 ( if x.lower() in ('a', 'e', 'i', 'o', 'u')
) 并返回推导式的长度,并将其反馈给sort
方法。
添加回答
举报