2011-08-05 141 views
3

我从CSV文件中提取一些电子邮件,然后将其保存到另一个CSV文件。将列表拆分为单个条目

电子邮件变量应该是这种格式:

email = ['[email protected]'], ['[email protected]'], ['[email protected]'] 

但在某些情况下,它也将被退回:

email = ['[email protected]', '[email protected]'], ['[email protected]'] 

在某些行找到2封电子邮件,所以这是当它是像这样呈现。

什么将是一种有效的方式来改变它?

+0

的可能重复[如何以最佳方式把一个多维列表到在Python项目的一个列表?(http://stackoverflow.com/questions/6679228/how-to-optimally-turn-a-multidimentional-list -INTO-A-单列表项功能于pyth的) – senderle

回答

0
data = [ ['[email protected]', '[email protected]'], ['[email protected]'] ] 

def flatten(data): 
    for item in data: 
     if isinstance(item, basestring): 
      yield item 
     else: 
      for i in item: 
       yield [i] 

,或者,如果你想支持嵌套的任意级别:

def flatten(data): 
    for item in data: 
     if isinstance(item, basestring): 
      yield [item] 
     else: 
      for i in flatten(item): 
       yield i 

如果您只需要邮件列表时,没有包裹在列表中的每个元素(这似乎更合理的给我) ,解决的办法是要简单得多:

import itertools 
print list(itertools.chain.from_iterable(data)) 
+0

是的,你是正确的,非常感谢你为你的输入!非常感激。 – sinnet3000

+0

为什么选择投票? – GaretJax

0

如果您正在使用CSV文件,则可能需要尝试从标准库中的CSV模块。 http://docs.python.org/library/csv.html

例子:

$ cat > test.csv 
['[email protected]', '[email protected]'], ['[email protected]'] 

$ python 
>>> import csv 
>>> reader = csv.reader(open('test.csv', 'r')) 
>>> for row in reader: 
...  print row 
... 
["['[email protected]'", " '[email protected]']", " ['[email protected]']"] 

我所做的有可能不是你想要什么,但如果你看看在图书馆你可能会发现你所需要的。