有用的20个python代码段(5)

329次阅读
没有评论

有用的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、列表取样

通过使用random软件库,以下代码从给定的列表中生成了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
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-15发表,共计1635字。
新手QQ群:570568346,欢迎进群讨论 Python51学习