练习1:
# l1 = [11,22,33]
# l2 = [22,33,44]
# a. 获取内容相同的元素列表
# b. 获取 l1 中有, l2 中没有的元素列表
# c. 获取 l2 中有, l1 中没有的元素列表
# d. 获取 l1 和 l2 中内容都不同的元素
# l1 = [11,22,33] # l2 = [22,33,44] # for i in l2: # if i not in l1: # print(i) # for i in l1: # if i not in l2: # print(i)
练习2:
12345678互相组合为一个2位数,两位数值不可重复
# count =0 # for i in range(1, 9): # for v in range(1, 9): # if i !=v: # count += 1 # # count = count -8 # print(count)
练习3:
99乘法表
# for i in range(1,10): # string = "" # for j in range(1,i+1): # string +=str(j) + " * "+str(i) + " = " +str(i*j)+" " # print(string)
# for i in range(1,10): # for j in range(1,i+1): # print(str(j) + " * "+str(i) + " = " +str(i*j)+" ",end="") # print(" ",end="") # 默认end= # print('alex', end='11') # print('alex','haifeng','gangniang',sep='11')
练习4:
[1,2,3,4]这里面的数字两个组合 多少种不同样的,数字不重复的
# li = [1,2,3,4] # l =len(li) # for i in range(0,l-1): # for v in range(i+1,l): # print(li[i],li[v])
练习5:
自动计算方案
百钱买小鸡
公鸡5文钱1只,母鸡三文钱一只,小鸡一文钱三只。现在用100文钱共买了100只鸡,
问这100只鸡中,公鸡,母鸡,小鸡各是多少只?
for x in range(1,100//5): for y in range(1,100//3): for z in range(1,100): if x + y + z == 100 and 5*x + 3*y + z/3 == 100: print(x,y,z)
练习6:
查找列表中元素,移除每个元素的空格,并查找以 a 或 A 开头 并且以 c 结尾的所有元素。
li = ["alec", " aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain")
dic = {'k1': "alex", 'k2': ' aric',"k3": "Alex", "k4": "Tony"}
#!/usr/bin/env python # -*- coding:utf-8 -*- li = ["alec", " aric", "Alex", "Tony", "rain"] for S in li: S = S.strip() prefix_a = S.startswith('a') prefix_A = S.startswith('A') suffix_c = S.endswith('c') if prefix_a or prefix_A and suffix_c: print('要查找的元素:%s' % S) tu = ("alec", " aric", "Alex", "Tony", "rain") for S in tu: S = S.strip() prefix_a = S.startswith('a') prefix_A = S.startswith('A') suffix_c = S.endswith('c') if prefix_a or prefix_A and suffix_c: print('要查找的元素:%s' % S) dic = {'k1': "alex", 'k2': ' aric',"k3": "Alex", "k4": "Tony"} for S in dic.values(): S = S.strip() prefix_a = S.startswith('a') prefix_A = S.startswith('A') suffix_c = S.endswith('c') if prefix_a or prefix_A and suffix_c: print('要查找的元素:%s' % S)
练习7:
有如下变量,请实现要求的功能
tu = ("alex", [11, 22, {"k1": 'v1', "k2": ["age", "name"], "k3": (11,22,33)}, 44])
-
讲述元祖的特性
- 请问 tu 变量中的"k2"对应的值是什么类型?是否可以被修改?如果可以,请在其中添加一个元素 “Seven”
# 元组的一级元素不可被修改增加删除,有序,可迭代,可切片,可索引,可转换为列表。 tu = ("alex", [11, 22, {"k1": 'v1', "k2": ["age", "name"], "k3": (11,22,33)}, 44]) v = tu[1][2]["k2"] v.append("Seven") print(tu)