1
投票
6答案
24081 次观看

如何按空格和行尾字符分割文件内容?

当我执行以下列表理解时,我会得到嵌套列表: channel_values = [x for x in [ y.split(' ') for y in open(channel_output_file).readlines() ] if x and not x == '\n'] 基本上我有一个包含以下内容的文件: 7656 7653 7649 7646 7643 7640 7637 7634 7631 7627 7624 7621 7618 7615 8626 8623 8620 8617 8614 8610 8607 8604 8600 8597 8594 8597...

2
投票
4答案
749 次观看

过滤奇数

M = [[1,2,3], [4,5,6], [7,8,9]] col2 = [row[1] + 1 for row in M if row[1] % 2 == 0] print (col2) 输出:[3, 9] 我希望它能过滤掉奇数,但是却相反。

8
投票
4答案
8307 次观看

Python:复杂的列表推导,其中一个变量依赖于另一个变量(对于测试中的t,x表示t中的x [t]中的x)

我想做类似的事情: all = [ x for x in t[1] for t in tests ] 测试如下: [ ("foo",[a,b,c]), ("bar",[d,e,f]) ] 所以我想得到结果 all = [a,b,c,d,e,f] 我的代码不起作用,Python说: UnboundLocalError: local variable 't' referenced before assignment 有没有简单的方法可以做到这一点?

87
投票
3答案
33014 次观看

反引号对python解释器意味着什么:`num`

我正在玩列表理解,并且在另一个站点上遇到了这个小片段: return ''.join([`num` for num in xrange(loop_count)]) 我花了几分钟尝试(通过键入)复制该功能,然后才意识到`num`位将其破坏。 用这些字符括起来的语句有什么作用?从我所看到的相当于str(num)。但是当我计时的时候: return ''.join([str(num) for num in xrange(10000000)]) 需要4.09秒,而: return ''.join([`num` for num in xrange(10000000)]) ...

17
投票
10答案
17988 次观看

Lambda vs列表理解性能

我最近发布了一个使用lambda函数的问题,有人在答复中提到lambda不再受欢迎,而是使用列表推导。我对Python比较陌生。我进行了一个简单的测试: import time S=[x for x in range(1000000)] T=[y**2 for y in range(300)] # # time1 = time.time() N=[x for x in S for y in T if x==y] time2 = time.time() print 'time diff [x for x in S for y in T if x==y]=', time2-time1 ...

1
投票
3答案
1328 次观看

将生成器表达式嵌套在python函数调用的参数列表中

有时我喜欢使用以下惯用法将列表组合在一起: >>> list(itertools.chain(*[[(e, n) for e in l] for n, l in (('a', [1,2]),('b',[3,4]))])) [(1, 'a'), (2, 'a'), (3, 'b'), (4, 'b')] (我知道有一些更简单的方法可以得到这个特定的结果,但是当您要遍历列表列表或类似的列表中的元素时,它会派上用场。麻烦的是,当您使用生成器时表达式,这容易出错。例如 >>> list(itertools.chain(*(((e, n) for ...

0
投票
3答案
560 次观看

Iterating through a list in Python

I am trying to iterate through a list and take each part of the list, encode it and join the result up when it is all done. As an example, I have a string which produces a list with each element being 16 characters in length. message = (u'sixteen-letters.sixteen-letters.sixteen-letters.sixteen-...

6
投票
4答案
432 次观看

Comprehensions in Python and Javascript are only very basic?

Looking at comprehensions in Python and Javascript, so far I can't see some of the main features that I consider most powerful in comprehensions in languages like Haskell. Do they allow things like multiple generators? Or are they just a basic map-filter form? If they don't allow multiple ge...

122
投票
6答案
55372 次观看

How to handle exceptions in a list comprehensions?

I have some a list comprehension in Python in which each iteration can throw an exception. For instance, if I have: eggs = (1,3,0,3,2) [1/egg for egg in eggs] I'll get a ZeroDivisionError exception in the 3rd element. How can I handle this exception and continue execution of the list comp...

7
投票
3答案
7407 次观看

Python: List comprehension to assign different values

I'm making a 2D list and I would like to initialize it with a list comprehension. I would like it to do something like this: [[x for i in range(3) if j <= 1: x=1 else x=2] for j in range(3)] so it should return something like: [[1,1,1], [1,1,1], [2,2,2]] How might I go about doing thi...

1
投票
6答案
437 次观看

List of Lists in python?

I need a good function to do this in python. def foo(n): # do somthing return list_of_lists >> foo(6) [[1], [2,3], [4,5,6]] >> foot(10) [[1], [2,3], [4,5,6] [7,8,9,10]]

1
投票
4答案
535 次观看

how to rewrite this loop in a more efficient way in python

I have a loop of the following type: a = range(10) b = [something] for i in range(len(a)-1): b.append(someFunction(b[-1], a[i], a[i+1])) However the for-loop is killing a lot of performance. I have try to write a windows generator to give me 2 elements everything time but it still require ...

0
投票
4答案
436 次观看

Verbose list comprehension in Python

I have a list of integers and I want to create a new list with all elements smaller than a given limit. a=range(15) #example list limit=9 #example limit My approach to solve this problem was [i for i in a if i < limit] To me the beginning 'i for i in' looks pretty verbose. Is there a bet...

19
投票
5答案
10849 次观看

Scala's for-comprehensions: vital feature or syntactic sugar?

When I first started looking at Scala, I liked the look of for-comprehensions. They seemed to be a bit like the foreach loops I was used to from Java 5, but with functional restrictions and a lot of sweet syntactic niceness. But as I've absorbed the Scala style, I find that every time I could us...

10
投票
5答案
11000 次观看

Mapping a nested list with List Comprehension in Python?

I have the following code which I use to map a nested list in Python to produce a list with the same structure. >>> nested_list = [['Hello', 'World'], ['Goodbye', 'World']] >>> [map(str.upper, x) for x in nested_list] [['HELLO', 'WORLD'], ['GOODBYE', 'WORLD']] Can this be do...

30
投票
2答案
8592 次观看

Is the order of results coming from a list comprehension guaranteed?

When using a list comprehension, is the order of the new list guaranteed in any way? As a contrived example, is the following behavior guaranteed by the definition of a list comprehension: >> a = [x for x in [1,2,3]] >> a [1, 2, 3] Equally, is the following equality guaranteed: &g...

74
投票
4答案
17228 次观看

Does PHP have an equivalent to Python's list comprehension syntax?

Python has syntactically sweet list comprehensions: S = [x**2 for x in range(10)] print S; [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] In PHP I would need to do some looping: $output = array(); $Nums = range(0,9); foreach ($Nums as $num) { $out[] = $num*=$num; } print_r($out); to get: Array...

752
投票
11答案
219410 次观看

List comprehension vs map

Is there a reason to prefer using map() over list comprehension or vice versa? Is either of them generally more efficient or considered generally more pythonic than the other?

15
投票
8答案
18908 次观看

convert string to dict using list comprehension

I have came across this problem a few times and can't seem to figure out a simple solution. Say I have a string string = "a=0 b=1 c=3" I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do thi...

9
投票
7答案
6664 次观看

List Comprehensions in Python : efficient selection in a list

Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a distance to an other element). I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code result = [ ( myFuncti...

236
投票
10答案
177929 次观看

Double Iteration in List Comprehension

In Python you can have multiple iterators in a list comprehension, like [(x,y) for x in a for y in b] for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions. My question is: Can one iterator in the comprehension refer to the other? In other...

0
投票
1答案
2179 次观看

one liner for conditionally replacing dictionary values

Is there a better way to express this using list comprehension? Or any other way of expressing this in one line? I want to replace each value in the original dictionary with a corresponding value in the col dictionary, or leave it unchanged if its not in the col dictionary. col = {'1':3.5, '6':...

4
投票
5答案
424 次观看

Is List-Comprehension any better than List-Abstractions?

Why do people prefer list comprehensions like (for [x '(1 2 3)] (* 2 x)) instead of (map #(* %1 2) '(1 2 3))? Are there benefits to this kind of programming? 1. Is it more readable? 2. Is it faster in some cases? 3. Is it better for certain kinds of operations and data structures?

1
投票
3答案
454 次观看

Tokenizing blocks of code in Python

I have this string: [a [a b] [c e f] d] and I want a list like this lst[0] = "a" lst[1] = "a b" lst[2] = "c e f" lst[3] = "d" My current implementation that I don't think is elegant/pythonic is two recursive functions (one splitting with '[' and the other with ']' ) but I am sure it can b...

10
投票
5答案
2996 次观看

Are list comprehensions a major part of Haskell?

I looked at various Haskell resources on the web, before buying the book, Real World Haskell. Being otherwise excellent, it doesn't seem to contain anything about list comprehensions which I saw mentioned in the various websites I looked at. Could this just be because they are generally unused in...

2
投票
6答案
8117 次观看

List comprehension python

What is the equivalent list comprehension in python of the following Common Lisp code: (loop for x = input then (if (evenp x) (/ x 2) (+1 (* 3 x))) collect x until (= x 1))

13
投票
3答案
7529 次观看

Perl等效于(Python-)列表理解

我正在寻找在Perl中表达此Python代码段的方法: data = {"A": None, "B": "yes", "C": None} key_list = [k for k in data if data[k]] # in this case the same as filter(lambda k: data[k], data) but let's ignore that 所以从一种角度来看,我只想要键值为 None 或 undef 的键。用另一种方式来看,我想要的是与清单理解的简洁Perl等效项有条件的。

10
投票
3答案
5036 次观看

Python:StopIteration异常和列表推导

我想从一个csv文件中读取最多20行: rows = [csvreader.next() for i in range(20)] 如果文件具有20行或更多行,则工作正常,否则将失败并显示StopIteration异常。 是否有一种优雅的方法来处理可能在列表理解中引发StopIteration异常的迭代器,还是应该使用常规的for循环?

3
投票
5答案
536 次观看

需要使用列表推导来改善Python代码的帮助

我一直在家里编写一些Python程序,以了解有关该语言的更多信息。我尝试了解的最新功能是列表推导。我创建了一个小脚本,根据我过去换油的频率来估算我的汽车何时需要下一次换油。在下面的代码段中,oil_changes是列出我换油的里程的列表。 # Compute a list of the mileage differences between each oil change. diffs = [j - i for i, j in zip(oil_changes[:-1], oil_changes[1:])] # Use the average difference between o...

76
投票
13答案
55157 次观看

python列表理解;压缩列表列表?

伙计们。我正在尝试找到问题的最优雅解决方案,并且想知道python是否为我想做的事情内置了任何东西。 我正在做的是这个。我有一个列表A,我有一个功能f,它接受一个项目并返回一个列表。我可以像这样使用列表推导来转换A中的所有内容; [f(a) for a in A] 但这会返回列表列表; [a1,a2,a3] => [[b11,b12],[b21,b22],[b31,b32]] 我真正想要的是获取扁平化列表; [b11,b12,b21,b22,b31,b32] 现在,其他语言都拥有它;在函数式编程语言中,传统上将其称为flatmap,而.Net...