12

彼らが少しの軽薄さを達成するために私が知らないかもしれないいくつかのPythonの魔法であるかどうか私は興味があります

次の行を指定します。

csvData.append(','.join([line.split(":").strip() for x in L]))

:行を分割し、その周りの空白を削除して、参加しようとしています,

問題は、配列がから返されるline.split(":")ため、

for x in L #<== L doesn't exist!

によって返される配列の名前がないため、問題が発生しますline.split(":")

だから、これを一発で達成するために使用できるセクシーな構文があるかどうか知りたいですか?

乾杯!

4

3 に答える 3

29
>>> line = 'a: b :c:d:e  :f:gh   '
>>> ','.join(x.strip() for x in line.split(':'))
'a,b,c,d,e,f,gh'

You can also do this:

>>> line.replace(':',',').replace(' ','')
'a,b,c,d,e,f,gh'
于 2012-09-12T04:54:23.213 に答える
1

文字列 S が与えられた場合:

','.join([x.strip() for x in s.split(':')])
于 2012-09-12T04:55:26.280 に答える
1

Something like?:

>>> L = "1:2:3:4"
>>> result = ",".join([item.strip() for item in L.split(":")])
>>> result
'1,2,3,4'

It takes awhile to get a grasp on list comprehensions. They are basically just packaged loops when you break them down.

So, when learning, try to break it down as a normal loop, and then translate it to a list comprehension.

In your example you don't assign the line variable anywhere, so it would be an error even in a standard loop.

>>> for x in L:
...     items = line.split(":")
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'line' is not defined
>>>
于 2012-09-12T04:53:56.627 に答える