2011-08-05 3 views
3

CSVファイルからいくつかの電子メールを抽出し、別のCSVファイルに保存しています。リストを個別のエントリに分割する

メール変数がこの形式である必要があります。

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

が、特定のケースでは、として返されます:それは2通の電子メールを見つけたので、それがあるときには、ある特定の行で

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

このように提示された。

これを変更する効率的な方法は何ですか?

+0

[多目的リストをPythonの単一項目リストに最適にする方法](http://stackoverflow.com/questions/6679228/how-to-optimally-turn-a-multidimentional-list) -into-a-item-in-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モジュールを試してみてください。私はあなたが望むものは存在しないかもしれませんでしたが、あなたはライブラリを見ればあなたが必要なものを見つけるかもしれない何

$ 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]']"] 

http://docs.python.org/library/csv.html

例。

関連する問題