• 技术文章 >Python技术 >Python基础教程

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

    尤及尤及2020-06-17 16:53:46转载1641

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

    更多Python知识,请关注:Python自学网!!

    专题推荐:python
    品易云
    上一篇:有用的20个python代码段(4) 下一篇:Python字符串操作常用知识点(2)

    相关文章推荐

    • Python中的9个代码小实例!• 有用的20个python代码段(2)• 有用的20个python代码段(3)• 有用的20个python代码段(4)

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网