Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python编写程序的最短方法_Python - Fatal编程技术网

用Python编写程序的最短方法

用Python编写程序的最短方法,python,Python,我想知道写以下内容的最短方法 res=[] for x in xrange(1,4): if x in [1,3]: res.append(1) else: res.append(0) 我的实际问题是将[4,6]这样的输入转换为[0,0,0,1,0,1],其中我使用xrange(1,7),例如使用列表理解: res = [int(x in (1, 3)) for x in xrange(1, 4)] 它利用了bool是in

我想知道写以下内容的最短方法

 res=[]
 for x in xrange(1,4):
     if x in [1,3]:
            res.append(1)
     else:
           res.append(0)

我的实际问题是将[4,6]这样的输入转换为[0,0,0,1,0,1],其中我使用xrange(1,7),例如使用列表理解:

res = [int(x in (1, 3)) for x in xrange(1, 4)]
它利用了
bool
int
的子类这一事实

更简短的当然是:

res = [1, 0, 1]
越短越好

res = [1, 0, 1]
这是另一种方式:

>>> [0 if i % 2 == 0 else 1 for i in range(1, 4)]
[1, 0, 1]

在这种情况下:

>>> map(int, '101')
[1, 0, 1]
根据您的评论:

>>> map(lambda e: int(e in [4,6]), xrange(1,7))
[0, 0, 0, 1, 0, 1]

我猜你在找这样的东西:

print[int(x在[4,6]中)表示范围(1,7)内的x]
输出:

[0, 0, 0, 1, 0, 1]

以下是我在内置博士学位的情况下的做法:

def bit_array(series, matches):
    """
    >>> bit_array(range(1, 7), (4, 6))
    [0, 0, 0, 1, 0, 1]
    >>> bit_array(range(1, 4), (1, 3))
    [1, 0, 1]
    """
    return [int(x in set(matches)) for x in series]

if __name__ == '__main__':
    from doctest import testmod
    testmod()

我不认为这是最短的,因为它是一个带参数的函数,并且有单元测试基础设施,但我认为它最清楚地表达了它的目的。而且,只要确信函数是有效的,您就可以将其内联并丢弃测试

试试这里:这个问题似乎是离题的,因为它要求进行一般的代码审查,即使示例很小,一般的意图也不清楚。最短的方法是
res=[1,0,1]
,这可能不是OP想要的。请求是:“请给我一个0和1的基于1的数组,其中输入是1的索引”?不应该是[1,0,1]?是的,我在写了答案后测试了它。你们都是对的。不,因为输出应该是
[1,0,1]
。Martijn您是对的。我的实际问题是将[4,6]这样的输入转换为[0,0,0,1,0,1],在这里我使用xrange(1,7),感谢Martijn。我不知道Bool是int的一个子类