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

how to write double nested for loops and not have a tuple as output

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

所以我有一个 url 我正在从中提取文本,我循环遍历文本以仅提取数字,然后将它们相加并 return 总数。

代码:

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

我尝试了几种优化嵌套循环的方法,但 none 给出了我想要的输出:

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

其中 return 编辑了与 numlist 相同的嵌套列表。预先感谢您的帮助。

标准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)))