function #14
Replies: 4 comments
-
元音字母个数def count_vowels(input_string):
# 定义元音字母
vowels = "aeiouAEIOU"
# 初始化计数器
count = 0
# 遍历字符串中的每个字符
for char in input_string:
if char in vowels:
count += 1
return count
# 示例使用
input_string = "Hello, World!"
print("元音字母的数量是:", count_vowels(input_string)) |
Beta Was this translation helpful? Give feedback.
0 replies
-
列表中第二大的元素编程思路还是比较直接的,遍历列表中每个数据,同时用两个变量分别保存当前遇到过的最大的两个数: def find_second_largest(numbers):
if len(numbers) < 2:
return None # 如果列表长度小于2,没有第二大元素
first_largest = second_largest = float('-inf') # 初始化两个变量为负无穷
for num in numbers:
if num > first_largest:
second_largest = first_largest # 更新第二大
first_largest = num # 更新第一大
elif first_largest > num > second_largest:
second_largest = num # 更新第二大
return second_largest if second_largest != float('-inf') else None
# 测试
numbers = [10, 20, 4, 45, 99]
result = find_second_largest(numbers)
if result is not None:
print(f"列表中的第二大元素是: {result}")
else:
print("列表中没有足够的元素来找到第二大值") |
Beta Was this translation helpful? Give feedback.
0 replies
-
字符串长度列表def string_lengths(strings):
lengths = [] # 初始化一个空列表来存储长度
for string in strings:
lengths.append(len(string)) # 计算每个字符串的长度并添加到列表中
return lengths
# 测试
words = ["apple", "banana", "cherry", "date"]
lengths = string_lengths(words)
print(f"字符串列表的长度是: {lengths}") |
Beta Was this translation helpful? Give feedback.
0 replies
-
订制披萨使用可变参数函数: def make_pizza(*toppings):
print("这个披萨试用了下列配料:")
for topping in toppings:
print(f" - {topping}")
make_pizza('香肠')
make_pizza('蘑菇', '青椒', '奶酪')我们还可以为函数增加一些额外信息: |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
function
创建字典
https://py.qizhen.xyz/function
Beta Was this translation helpful? Give feedback.
All reactions