相关疑难解决方法(0)

在块中迭代列表的最"pythonic"方法是什么?

我有一个Python脚本,它将整数列表作为输入,我需要一次使用四个整数.不幸的是,我无法控制输入,或者我将它作为四元素元组列表传入.目前,我正在以这种方式迭代它:

for i in xrange(0, len(ints), 4):
    # dummy op for example code
    foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3]
Run Code Online (Sandbox Code Playgroud)

它看起来很像"C-think",这让我怀疑有更多的pythonic方式来处理这种情况.迭代后会丢弃该列表,因此无需保留.也许这样的事情会更好吗?

while ints:
    foo += ints[0] * ints[1] + ints[2] * ints[3]
    ints[0:4] = []
Run Code Online (Sandbox Code Playgroud)

但是,仍然没有"感觉"正确.: - /

相关问题:如何在Python中将列表拆分为大小均匀的块?

python optimization loops list chunks

449
推荐指数
15
解决办法
12万
查看次数

Python"Every Other Element"成语

我觉得我花了很多时间在Python中编写代码,但没有足够的时间创建Pythonic代码.最近我遇到了一个有趣的小问题,我认为可能有一个简单,惯用的解决方案.解释原文,我需要收集列表中的每个连续对.例如,给定列表[1,2,3,4,5,6],我想计算[(1,2),(3,4),(5,6)].

我想出了一个看起来像翻译Java的快速解决方案.重温这个问题,我能做的最好的就是

l = [1,2,3,4,5,6]
[(l[2*x],l[2*x+1]) for x in range(len(l)/2)]
Run Code Online (Sandbox Code Playgroud)

在长度不均匀的情况下,其具有抛弃最后一个数字的副作用.

是否有一种我不知道的惯用方法,或者这是我最好的方法?

python idioms

38
推荐指数
4
解决办法
3万
查看次数

最小化if函数中的if语句

我有以下函数,它从pandas dataframe列获取值并提供参数(s0_loc,s1_loc,.. upto ..,s12_loc,当且仅当它们各自的s0,s1,s2 ...,s12不为空时)到另一个功能.另外,当且仅当s0不为空时,它将检查s1是否为空...类似地,它将检查s2是否为空,如果是s0,则s1不为空.所以...

根据以上标准,我写了以下功能.但它的功能很长......我想减少这个函数中的代码片段.

def compare_locality(p,p_loc,s0,s0_loc,s1,s1_loc,s2,s2_loc,s3,s3_loc,s4,s4_loc,s5,s5_loc,s6,s6_loc,s7,s7_loc,s8,s8_loc,s9,s9_loc,s10,s10_loc,s11,s11_loc,s12,s12_loc):
    loc = []
    if s0 != '' :
        loc.append(s0_loc)
        if s1 != '' :
            loc.append(s1_loc)
            if s2 != '' :
                loc.append(s2_loc)
                if s3 != '' :
                    loc.append(s3_loc)
                    if s4 != '' :
                        loc.append(s4_loc)
                        if s5 != '' :
                            loc.append(s5_loc)
                            if s6 != '' :
                                loc.append(s6_loc)
                                if s7 != '' :
                                    loc.append(s7_loc)
                                    if s8 != '' :
                                        loc.append(s8_loc)
                                        if s9 != '' :
                                            loc.append(s9_loc)
                                            if s10 != '' :
                                                loc.append(s10_loc)
                                                if s11 != …
Run Code Online (Sandbox Code Playgroud)

python dataframe pandas

1
推荐指数
1
解决办法
74
查看次数

标签 统计

python ×3

chunks ×1

dataframe ×1

idioms ×1

list ×1

loops ×1

optimization ×1

pandas ×1