知行编程网知行编程网  2022-12-31 17:00 知行编程网 隐藏边栏  2 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于有用的20个python代码段(5)的相关知识,包括一段python代码,以及python和c++的区别这些编程知识,希望对大家有参考作用。

20 个有用的 Python 代码片段(5)


有用的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

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享