Py学习  »  Python

给我看一些很酷的python列表理解[关闭]

christangrant • 4 年前 • 931 次点击  

python和其他一些(函数式)编程语言的主要优点之一是 list comprehension . 它们允许程序员在一行中编写复杂的表达式。它们一开始可能会让人困惑,但如果习惯了语法,就比嵌套复杂for循环好得多。

尽管如此,请与我分享清单理解的一些最酷的用法。(酷,我的意思是有用的)它可能是一些编程比赛,或生产系统。

例如: 做矩阵的转置 mat

>>> mat = [
...        [1, 2, 3],
...        [4, 5, 6],
...        [7, 8, 9],
...       ]

>>> [[row[i] for row in mat] for i in [0, 1, 2]]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

请包括表达式的描述和使用位置(如果可能)。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49958
 
931 次点击  
文章 [ 8 ]  |  最新文章 4 年前
Pierce
Reply   •   1 楼
Pierce    13 年前

只要您对Python中受函数编程启发的部分感兴趣,就可以考虑使用Python提供的map、filter、reduce和zip。

Peter Milley
Reply   •   2 楼
Peter Milley    13 年前

我目前有几个脚本,需要将一组点按高度分组为“级别”假设点的z值将松散地聚集在与级别相对应的特定值周围,并且在聚集之间有较大的ish间隙。

所以我有以下功能:

def level_boundaries(zvalues, threshold=10.0):
    '''Finds all elements z of zvalues such that no other element
    w of zvalues satisfies z <= w < z+threshold.'''
    zvals = zvalues[:]
    zvals.sort()
    return [zvals[i] for i, (a, b) in enumerate(pairs(zvals)) if b-a >= threshold]

“pairs”直接取自itertools模块文档,但仅供参考:

def pairs(iterable):
    'iterable -> (iterable[n], iterable[n+1]) for n=0, 1, 2, ...'
    from itertools import izip, tee
    first, second = tee(iterable)
    second.next()
    return izip(first, second)

一个虚构的使用示例(我的实际数据集太大,无法用作示例):

>>> import random
>>> z_vals = [100 + random.uniform(-1.5,1.5) for n in range(10)]
>>> z_vals += [120 + random.uniform(-1.5,1.5) for n in range(10)]
>>> z_vals += [140 + random.uniform(-1.5,1.5) for n in range(10)]
>>> random.shuffle(z_vals)
>>> z_vals
[141.33225473458657, 121.1713952666894, 119.40476193163271, 121.09926601186737, 119.63057973814858, 100.09095882968982, 99.226542624083109, 98.845285642062763, 120.90864911044898, 118.65196386994897, 98.902094334035326, 121.2741094217216, 101.18463497862281, 138.93502941970601, 120.71184773326806, 139.15404600347946, 139.56377827641663, 119.28279815624718, 99.338144106822554, 139.05438770927282, 138.95405784704622, 119.54614935118973, 139.9354467277665, 139.47260445000273, 100.02478729763811, 101.34605205591622, 138.97315450408186, 99.186025111246295, 140.53885845445572, 99.893009827114568]
>>> level_boundaries(z_vals)
[101.34605205591622, 121.2741094217216]
Tamás
Reply   •   3 楼
Tamás    13 年前

在加载以哈希标记开头的可选注释行的制表符分隔文件时,我始终使用此选项:

data = [line.strip().split("\t") for line in open("my_file.tab") \
        if not line.startswith('#')]

当然,它也适用于任何其他注释和分隔符字符。

Neil
Reply   •   4 楼
Neil    13 年前

如果“酷”意味着疯狂,我喜欢这个:

def cointoss(n,t):
    return (lambda a:"\n".join(str(i)+":\t"+"*"*a.count(i) for i in range(min(a),max(a)+1)))([sum(randint(0,1) for _ in range(n)) for __ in range(t)])

>>> print cointoss(20,100)
3:    **
4:    ***
5:    **
6:    *****
7:    *******
8:    *********
9:    *********
10:   ********************
11:   *****************
12:   *********
13:   *****
14:   *********
15:   *
16:   **

n和t控制每次测试抛硬币的次数,以及测试运行和绘制分布的次数。

Grumdrig
Reply   •   5 楼
Grumdrig    13 年前

要展平列表列表,请执行以下操作:

>>> matrix = [[1,2,3], [4,5,6]]
>>> [x for row in matrix for x in row]
[1, 2, 3, 4, 5, 6]
Mark Byers
Reply   •   6 楼
Mark Byers    13 年前

做矩阵的转置 mat :

>>> [list(row) for row in zip(*mat)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Nick Johnson
Reply   •   7 楼
Nick Johnson    13 年前

我经常用理解来构建口述:

my_dict = dict((k, some_func(k)) for k in input_list)

注意,Python 3有dict理解,因此这变成:

my_dict = {k:some_func(k) for k in input_list}

从元组列表中构造类似CSV的数据:

data = "\n".join(",".join(x) for x in input)

实际上不是列表理解,但仍然有用:从“切点”列表中生成范围列表:

ranges = zip(cuts, cuts[1:])
kerkeslager
Reply   •   8 楼
kerkeslager    13 年前

很多人不知道Python允许您使用 if :

>>> [i for i in range(10) if i % 2 == 0]
[0, 2, 4, 6, 8]