Bootstrap

列表的练习


# 1. 求15的阶乘
s = 1
for i in range(1, 16):
    s *= i
print(f"15的阶乘是{s}")

# 2.有一个棋盘,有64个方格,在第一个方格里面放1粒芝麻重量是0.00001kg,
#   第二个里面放2粒,第三个里面放4...,求棋盘上放的所有芝麻的重量
s = 0
for i in range(64):
    s += 2 ** i
print(f"所有芝麻的重量是{s*0.00001}kg")

# 3. 求1/1! + 1/2! + 1/3! + ..... 1/20!的结果
s = 0
c = 1
for i in range(1, 21):
    c *= i
    s += 1/c
print(s)

# 方法2
'''
import math
s = 0
for i in range(1, 21):
    s += 1/math.factorial(i)
print(s)
'''
# 4. 已知列表list1 = ['mon','sun','sat','fri','thu','wed'],
#    list2 = ['sun','wed','thu'],将属于list2的元素从list1中删除
list1 = ['mon', 'sun', 'sat', 'fri', 'thu', 'wed']
list2 = ['sun', 'wed', 'thu']
for n in list2:
    while n in list1:
        list1.remove(n)
print(list1)

# 方法二:
list1 = ['mon', 'sun', 'sat', 'fri', 'thu', 'wed']
list2 = ['sun', 'wed', 'thu']
list3 = []
for n in list1:
    if n not in list2:
        list3.append(n)
print(list3)


# 不建议使用del删除数据

# 5. 已知一个列表names = ['鲁班七号','后裔', '狄仁杰', '黄忠', '孙尚香'],
#    编写程序用两种方法获取names中的元素黄忠
names = ['鲁班七号', '后裔', '狄仁杰', '黄忠', '孙尚香']
print(names[-2])
print(names[3])
print(names[3:4][0])
print(names[-2:-1][0])
print(names[-2:-3:-1][0])

# 6. 已知一个数字列表nums = [1, 2, 3,1, 4, 2, 1 ,3, 7, 3, 3],输出索引为奇数的元素
nums = [1, 2, 3, 1, 4, 2, 1, 3, 7, 3, 3]
for i in range(len(nums)):
    if i % 2:
        print(i, nums[i])

for i in range(1, len(nums), 2):
    print(i, nums[i])

print(nums[1::2])

for i, n in enumerate(nums):
    if i % 2:
        print(i, n)

;