美文网首页疯狂Python讲义
3.Python-列表、元组和字典

3.Python-列表、元组和字典

作者: Kan_shan | 来源:发表于2019-07-20 12:02 被阅读0次
image.png

case3.1:生成指定数量的随机数...

# -*- coding:utf-8 -*-
# Copyright (c)2019, KanShan,All rightsreserved
# Author:KanShan
#Description:输入N个整数,生成N个随机的...
import random
import string

num = input("请输入一个整数:")
int_num = int(num)
a_list = [random.randrange(0,999,2)+1 for _ in range(int_num)] #1000以内随机奇数
b_list = [random.randint(1,1000) for _ in range(int_num)]  #10001以内随机整数
c_list = [random.choice(string.ascii_uppercase) for _ in range(int_num)] #随机大写字符
d_list = [random.sample(string.ascii_lowercase,2) for _ in range(int_num)] #随机2位小写字符
e_list = [random.choice(string.ascii_letters) for _ in range(int_num)] #随机字符
f_list = [random.choice(string.digits) for _ in range(int_num)] #随机数字
h_list = [random.random() for _ in range(int_num)] #小于1的随机数
i_list = [random.uniform(1,3) for i in range(int_num)] #1~3之间的随机数
print(a_list)
print(b_list)
print(c_list)
print(d_list)
print(e_list)
print(f_list)
random.shuffle(f_list) #打乱顺序
print(f_list)
print(h_list)
print(i_list)
image.png

case3.2:去除列表中重复元素

# -*- coding:utf-8 -*-
# Copyright (c)2019, KanShan,All rightsreserved
# Author : KanShan
#Description :输入多个字符串存入到列表中,去除重复的子串后输出
input_str = input("请输入多个字符串,用空格隔开:")
input_list = input_str.split()
b_list = []
#方法二
#[b_list.append(i) for i in input_list if not i in b_list]
#方法三
#b_list = set(input_list)
for i in input_list:
    if not i in b_list:
        b_list.append(i)
print(b_list)

case3.3:使用dict统计次数

# -*- coding:utf-8 -*-
# Copyright (c)2019, KanShan,All rightsreserved
# Author : KanShan
#Description :随机1000个:数字+字符+符号,统计次数
import random
import string

string_chars = string.digits + string.ascii_letters + string.punctuation
random_list= [random.choice(string_chars) for i in range(1000)]
new_dict = dict()
for ch in random_list:
    new_dict[ch] = new_dict.get(ch,0) +1
print(new_dict)

思维导图


3.列表、元组和字典.jpeg

相关文章

网友评论

    本文标题:3.Python-列表、元组和字典

    本文链接:https://www.haomeiwen.com/subject/hxgylctx.html