1.如何实现 “1,2,3” 变成 [‘1’,’2’,’3’] ? 如何实现[‘1’,’2’,’3’]变成[1,2,3] ?(代码题)
# 第一个问题
str1 = "1,2,3"
list1 = [i for i in str1.split(",")]
print(list1)
# 第二个问题
list2 = ['1', '2', '3']
list3 = [int(i) for i in list1]
print(list3)
2. 1、2、3、4、5 能组成多少个互不相同且无重复的三位数(代码题)
count = 0
for i in range(1, 6):
for k in range(1, 6):
for j in range(1, 6):
if i != k and i != j and k != j:
count += 1
print(str(i) + str(j) + str(k))
print("共组成%d个不重复的三位数" % count)
3.比较: a = [1,2,3] 和 b = [(1),(2),(3) ] 以及 c = [(1,),(2,),(3,) ] 的区别?(简答题)
a和b都是列表,c是元祖列表
4.两个列表 colors=['balck',"white"] sizes=["S","M","L"],请严格按照顺序输出如下结果
:[('balck', 'S'), ('white', 'S'), ('balck', 'M'), ('white', 'M'), ('balck', 'L'), ('white', 'L')] (按照尺码逆序排列)(代码题)
两种方法
# 方法一
colors = ['balck', "white"]
sizes = ["S", "M", "L"]
list1 = [(c, s) for s in sizes for c in colors]
print(list1)
# 方法二
colors = ['balck', "white"]
sizes = ["S", "M", "L"]
list1 = list()
for s in sizes:
for c in colors:
list1.append((c, s))
print(list1)
5.有两个6面骰子,同时抛掷100000次,求两个骰子点数只和所占百分比,如下:
(注意:字典顺序可以不一致,由于是概率性问题,字典的值会有浮动)(代码题)
{2: '2.78%', 3: '5.59%', 4: '8.33%', 5: '10.92%', 6: '13.93%', 7: '16.68%', 8: '13.94%', 9: '11.13%', 10: '8.44%', 11: '5.53%', 12: '2.72%'}
import random
list1 = list()
dict1 = dict()
for i in range(100000):
a = random.randint(1, 6)
b = random.randint(1, 6)
list1.append(a + b)
for data in set(list1):
dict1[data] = "{:.2%}".format(list1.count(data) / 100000)
print(dict1)