python 列表问题 ?
大家讲道理
大家讲道理 2017-04-17 18:01:28
0
4
392

新手勿喷

for i in  open (v):
    _temp = i.split('-')
    self._i= gen.gen(_temp[0], _temp[1])

self._i 中是多个列表[] [] [] 怎样合并成一个


cc = []
for i in  open (v):
    _temp = i.split('-')
    self= gen.gen(_temp[0], _temp[1])
    for bbc in  self:
        cc.append(i)

这样解决的 !!!

怎样把结果赋值给 self._i

 self._i = cc
    print 出来是空白 
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
大家讲道理

If you mean to merge multiple lists into one, then it is best to use itertools.chain to concatenate. The following is a simple example:

>>> from itertools import chain
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [7,8,9]
>>> chain(a,b,c)
<itertools.chain object at 0x7f2915465c10>
>>> list(chain(a,b,c))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

For your case:

from itertools import chain
lst = list(chain(*self._i))

The following digression.

@松林's method is feasible, and the performance will not be bad. In python, the behaviors of amplification (enhanced) operation and general operation are not necessarily exactly the same. Here we use + to discuss.

Let’s look at an example:

>>> lst1 = [1,2,3]
>>> lst2 = [4,5,6]
>>> id(lst1)
139814427362656
>>> id(lst1 + lst2)
139814427363088
>>> lst1 += lst2
>>> id(lst1)
139814427362656

From this example, we can find that lst1 + lst2 會產生一個新的 list,但是 lst1 += lst2 will not, because for the amplification operation, Python most will follow the following rules:

  1. The immutable type will generate a new object after operation, and let the variables refer to the object

  2. Variable types will use in-place operations to expand or update the object that the variable originally refers to

In other words lst1 += lst2 等價於 lst1.extend(lst2)

It depends on whether the type is implemented __iadd__(或 __imul__ ...) 而不是只有實作 __add__ (或 __mul__ ...)

If there is no implementation __iXXX__ 的型態,Python 會改呼叫 __XXX__ 代替,這一定會運算出新的 object,但是 __iXXX__, the original object will be updated in place

In other words, most of:

  1. Immutable types will not be implemented __iXXX__, because it makes no sense to update an immutable object

  2. Variable types will be implemented __iXXX__ Come and update on the spot

Why do I keep emphasizing the majority?

Because it is optimized in CPython str 的擴增運算,str += other and it is so commonly used. When concatenating, Python will not copy the string every time


Questions I answered: Python-QA

小葫芦

Use the extend function, such as:

>>> a=[1,2,3]
>>> b=[4,5,6]
>>> c=[7,8,9]
>>> d=[]
>>> d.extend([a,b,c])
>>> d
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
洪涛

Using addition will be more intuitive, but the performance will be worse

ret = []
for x in self._i:
    ret += x
print(x)
左手右手慢动作

Is this more Pythonic?

myList = [x for j in self._i for x in j]
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template