如何编写双嵌套for循环并且没有元组作为输出

时间:2015-10-29 03:54:33

标签: python list-comprehension

出于优化目的和教育,我想知道如何编写优化的双嵌套循环。我尝试了其他一些看起来相似但碰到砖墙问题的选项。

所以我有一个我正在提取文本的网址,我循环浏览文本只提取数字,然后将它们相加并返回总数。

代码:

import urllib
import re
from itertools import combinations

url = urllib.urlopen('http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/\
regex_sum_185517.txt')

total = 0

numlist = [re.findall('[0-9]+',line.rstrip()) for line in url]

#then I want to iterate through numlist twice to extract the numbers and sum them up.

for numb in numlist:
    for nu in numb:
        total = total + int(nu)

print total

我尝试了几种方法来优化嵌套循环,但没有一种方法能够为我提供所需的输出:

for nu in combinations(numlist,2):
    total = total + int(nu)
    print total

返回:

TypeError: int() argument must be a string or a number, not 'tuple'

我也尝试过:

total = [[total + int(nu) for nu in numb] for numb in numblist]
print total

返回与numlist中相同的嵌套列表。感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

标准flatten a single level of nesting pattern inlined

from future_builtins import map   # Only on Python 2 to avoid intermediate list
from itertools import chain

total = sum(map(int, chain.from_iterable(numlist)))