生成随机数列表 list1

import random

list1 = []
# 前 10 个元素为 0-1 的小数
for i in range(10):
    list1.append(random.random())

# 11-20 个元素为整数
for i in range(11, 21):
    list1.append(random.randint(1, 100))

print('list1:', list1)

输出:

list1: [0.7982468164993963, 0.8184653218525413, 0.12191430968706931, 0.3136175239598812, 0.2623057619184386, 0.5937697046196499, 0.700905627988178, 0.1428473793466558, 0.3966182862462639, 0.2324262651598921, 73, 4, 63, 68, 52, 84, 6, 77, 43, 34]

在列表 list1 后加入新的列表 list2

list2 = [99, 89, 98, 78, 96, 97, 60, 90, 100, 771]
list1.append(list2)

print('list1:', list1)

输出:

list1: [0.7982468164993963, 0.8184653218525413, 0.12191430968706931, 0.3136175239598812, 0.2623057619184386, 0.5937697046196499, 0.700905627988178, 0.1428473793466558, 0.3966182862462639, 0.2324262651598921, 73, 4, 63, 68, 52, 84, 6, 77, 43, 34, [99, 89, 98, 78, 96, 97, 60, 90, 100, 771]]

对列表 list1 中的 list2 进行排序,并返回元素 100 的位置:

list2.sort()
index = list2.index(100)
print('list2:', list2)
print('index of 100 in list2:', index)

# 从 list1 中删除 list2
list1.remove(list2)

输出:

list2: [60, 78, 89, 96, 97, 98, 99, 100, 771]
index of 100 in list2: 7
Python 列表操作:生成随机数列表,添加子列表,排序并查找元素位置

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

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