1. 编写一个程序,找出给定列表中的所有重复项,并将它们存储在一个新列表中。例如,如果列表为[1, 2, 3, 2, 1, 4, 5, 4],则程序应该返回[1,2,4]。

答案:

def find_duplicates(lst):
    duplicates = []
    for i in range(len(lst)):
        for j in range(i+1, len(lst)):
            if lst[i] == lst[j] and lst[i] not in duplicates:
                duplicates.append(lst[i])
    return duplicates

lst = [1, 2, 3, 2, 1, 4, 5, 4]
print(find_duplicates(lst))
  1. 编写一个程序,接受一个字符串,并计算其中每个字符出现的次数。例如,如果输入的字符串为“hello”,则程序应该返回{'h': 1, 'e': 1, 'l': 2, 'o': 1}。

答案:

def count_chars(s):
    counts = {}
    for char in s:
        if char in counts:
            counts[char] += 1
        else:
            counts[char] = 1
    return counts

s = "hello"
print(count_chars(s))
  1. 编写一个程序,接受一个整数列表,并返回其中所有元素的平均值。例如,如果列表为[1, 2, 3, 4, 5],则程序应该返回3.0。

答案:

def average(lst):
    total = 0
    for num in lst:
        total += num
    return total / len(lst)

lst = [1, 2, 3, 4, 5]
print(average(lst))
给出3个python关于循环的有点难度的题目和答案

原文地址: http://www.cveoy.top/t/topic/bL1q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录