导语:
本文主要介绍了关于有用的20个python代码段(5)的相关知识,包括一段python代码,以及python和c++的区别这些编程知识,希望对大家有参考作用。
有用的20个python代码段(5):
1、列表清单扁平化
有时你不确定你的列表可以嵌套多深,而你只想将所有元素放在一个平面列表中。
可以通过以下方式获得:
from iteration_utilities import deepflatten
# if you only have one depth nested_list, use this
def flatten(l):
return [item for sublist in l for item in sublist]
l = [[1,2,3],[3]]
print(flatten(l))
# [1, 2, 3, 3]
# if you don't know how deep the list is nested
l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]
print(list(deepflatten(l, depth=3)))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
若有正确格式化的数组,Numpy扁平化是更佳选择。
2、列表取样
使用随机软件库,以下代码从给定列表中生成 n 个随机样本。
import random
my_list = ['a', 'b', 'c', 'd', 'e']
num_samples = 2
samples = random.sample(my_list,num_samples)
print(samples)
# [ 'a', 'e'] this will have any 2 random values
强烈建议使用 secrets 库生成随机样本进行加密。
以下代码仅限用于Python 3。
import secrets # imports secure module.
secure_random = secrets.SystemRandom() # creates a secure random object.
my_list = ['a','b','c','d','e']
num_samples = 2
samples = secure_random.sample(my_list, num_samples)
print(samples)
# [ 'e', 'd'] this will have any 2 random values
3、数字化
以下代码将一个整数转换为数字列表。
num = 123456
# using map
list_of_digits = list(map(int, str(num)))
print(list_of_digits)
# [1, 2, 3, 4, 5, 6]
# using list comprehension
list_of_digits = [int(x) for x in str(num)]
print(list_of_digits)
# [1, 2, 3, 4, 5, 6]
4、检查唯一性
以下函数将检查列表中的所有元素是否都是唯一的。
def unique(l):
if len(l)==len(set(l)):
print("All elements are unique")
else:
print("List has duplicates")
unique([1,2,3,4])
# All elements are unique
unique([1,1,2,3])
# List has duplicates
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ Python排序函数及用法09/13
- ♥ python中的集合范围如何更具包容性?12/07
- ♥ 如何在python中保存文本文件11/23
- ♥ Python如何实现队列的同步12/02
- ♥ 获取python元组元素的方法有哪些09/11
- ♥ python上下文管理器关闭的应用09/21
内容反馈