2017-05-25 108 views
0

我正在尝试为网站上的某些术语创建唯一名称和网格位置的列表。尽管我的代码看起来有点复杂,但我认为我想实现的目标非常简单。获取循环的总循环数INSIDE另一个循环

我已经创建了一个枚举for循环内另一个枚举for循环,我在我的代码中的星星我想输入的东西,将反映该程序执行循环的总数。因此,如果我的名为“watch_link_urls”的第一个列表是4个项目,而名为“watch_model_description”的第二个列表是7个项目,那么我应该总共有28个循环。我应该在包含星号的括号中放置什么,以便变量“watch_model_description”和“watch_model_description_grid”会一直读到“category_1 =”...,“category_2 =”...等等直至“category_28”?

watch_model_description_list = [] 
watch_model_description_grid_list = [] for num, url in enumerate(watch_link_urls): 
    dennisov_model_html = urlopen(url).read() 
    watch_model_description = findall("dib_02'\>([A-Z \/0-9]+)\<", dennisov_model_html) 
    for number, category in enumerate(watch_model_description): 
     watch_model_description = 'category_' + str(**********) + ' = Label(window, text = "'+ category +'")' 
     watch_model_description_grid = 'category_' + str(**********) + '.grid(padx = 5, pady = 0, row = ' + str(number+3) + ', column = '+ str(num) +')' 

编辑:包括以下全部代码,以帮助调试

from Tkinter import Tk, Button, Canvas, END, Spinbox, PhotoImage, Label 
from ttk import Progressbar, Combobox 
from urllib import urlopen 
from re import findall 
import re 
import itertools 
import urllib 

## Create a window 
window = Tk() 

## Give the window a title 
window.title('Watch finder') 

## Show Dennisov image logo 
dennisov_logo_url = "http://i.imgur.com/KD6AK08.gif" 
handle = urlopen(dennisov_logo_url) 
data = handle.read() 
raw_image = PhotoImage(master = window, data = data) 
Label(window, image = raw_image, width = 600).grid(row = 0, column = 0, columnspan = 10) 
handle.close 

## Types of Dennisov watches 
dennisov_type_list = ['Barracuda Limited','Barracuda Chronograph', 
         'Barracuda Mechanical','Speedster','Free Rider', 
         'Nau Automatic','Lady Flower','Enigma','Number One'] 

dennisov_file = open('dennisov_url.html', 'w') 

dennisov_file.write(''' 
<!DOCTYPE html> 
<html> 
    <head> 
     <title>Watches</title> 
    </head> 
    <body> 
''') 

#### Display the quanity of watches available for each type 
##quantity_box = len(watch_option) 
## 
#### 
##for watch, number in enumerate(watch_option): 
## watch_number_name = watch_option[number][0] 
## watch_number_image = watch_option[number][1] 
## watch_number_price = watch_option[number][2] 
## watch_number_link = watch_option[(number)][3] 
#### dennisov_file.write('<h1>' + watch_number_name + '</h1>') 
## print watch_number_image 
#### dennisov_file.write('<img src="' + watch_number_image + '">\n') 
## print watch_number_price 
#### dennisov_file.write('<h2>' + watch_number_price + '</h2>') 
## print watch_number_link 
#### dennisov_file.write('<a href="'+watch_number_link+'">'+watch_number_link+'</a>') 
##  

dennisov_file.write(''' 
</body> 
</html> 
''') 

## Define function for button push 
def display_choice(): 

    dennisov_type_selection = (dennisov_dropdown_box.get()) 
    if dennisov_type_selection == 'Barracuda Limited': 
     dennisov_type = 'barracuda_limited' 
    elif dennisov_type_selection == 'Barracuda Chronograph': 
     dennisov_type = 'barracuda_chronograph' 
    elif dennisov_type_selection == 'Barracuda Mechanical': 
     dennisov_type = 'barracuda_mechanical' 
    elif dennisov_type_selection == 'Speedster': 
     dennisov_type = 'speedster' 
    elif dennisov_type_selection == 'Free Rider': 
     dennisov_type = 'free_rider' 
    elif dennisov_type_selection == 'Nau Automatic': 
     dennisov_type = 'nau_automatic' 
    elif dennisov_type_selection == 'Lady Flower': 
     dennisov_type = 'lady_flower' 
    elif dennisov_type_selection == 'Enigma': 
     dennisov_type = 'enigma' 
    elif dennisov_type_selection == 'Number One': 
     dennisov_type = 'number_one' 

    dennisov_url = 'https://denissov.ru/en/'+ dennisov_type + '/' 
    dennisov_url_subpage = dennisov_url[19:] 
## dennisov_url_subpage_subpage = dennisov_url_subpage[ 

    ## Make the html document just created equal to an opened and read URL???? 
    ##??????????????????????????????????????????????????????????????????? 
    dennisov_html = urlopen(dennisov_url).read() 
    ## Replace instances of double quotation marks in the text with singles 
    ## so that the findall regex code does not get confused 
    dennisov_html = dennisov_html.replace('"', "'") 

    ## Find all of the images of the watches. Each watch image starts with the text 
    ## "img src=". Do not match those with any " symbols in the URL 
    watch_image_urls = findall("<img src='(/files/collections/o[^']*)'", dennisov_html) 
    ## Add the URL domain to each watch image subpage to create full addresses 
    watch_image_urls = ['https://denissov.ru' + remainder for remainder in watch_image_urls] 
    ## dennisov_file.write('  <img src="' + image + '">\n') 
    ## Download and save the PNG images to the directory as GIFs so that 
    ## Tkinter can use them 

    ## Return the watch type. The watch type is in a title tag called "titlusref" 
    ## and can be any combination of letters and spaces, followed by a space and 
    ## "<" symbol. 
    watch_type = findall("titlusref'\>([a-zA-Z]+ *[a-zA-Z]*) *\<", dennisov_html)[0] 

    ## Find all of the links when each watch is clicked. Each watch link starts 
    ## with the text "a href=" followed by the subpage, followed by any 
    ## letter, number and "_" symbol combination, followed by a backslash 
    watch_link_urls = findall("a href='" + (dennisov_url_subpage) + "([A-Za-z0-9_]+/)", dennisov_html) 
    ## Add the main URL to each watch subpage 
    watch_link_urls = [str(dennisov_url) + remainder for remainder in watch_link_urls] 


    ## Find all of the model numbers of each watch. Each model starts with the text 
    ## "covername" then any combination of letters, dots and spaces. 
    watch_models = findall("covername'>([A-Z a-z0-9\.]+)", dennisov_html) 
    ## Add the watch type to each watch model, seperated by a space, to create the 
    ## full watch names 
    watch_names = [str(watch_type) + " " + remainder for remainder in watch_models] 

    ## Get current USD to AUD exchange rate using a known currency website 
    currency_converter_url = 'http://www.xe.com/currencyconverter/convert/?From=USD&To=AUD' 
    currency_html = urlopen(currency_converter_url).read() 
    ## Replace instances of double quotation marks in the text with singles 
    ## so that the findall regex code does not get confused 
    currency_html = currency_html.replace('"', "'") 
    ## Find the exchange rate. The exchange rate starts with "uccResultAmount'>" 
    ## and is then followed by any combination of numbers with a decimal place 
    exchange_rate = float(findall("uccResultAmount'\>([0-9]+\.[0-9]*)", currency_html)[0]) 

    ## Find the price of the models and make into floats. Each model price contains 
    ## numbers followed by the text "USD" 
    USD_watch_prices = [float(price) for price in (findall("([0-9]*) usd", dennisov_html))] 
    ## Convert the USD watch prices to current AUD prices and round to 2 decimals 
    watch_prices = [round(exchange_rate*price, 2) for price in USD_watch_prices] 
    ## Add the currency to the prices 
    watch_prices = ["AU $" + str(price) for price in watch_prices] 

    ## Match each watch name to its image and URL inside a tuple and place each 
    ## tuple inside a list 
    watch_list = zip(watch_names, watch_image_urls, watch_prices, watch_link_urls) 
    ## For each watch tuple (matching image, name and URL), assign a watch number 
    watch_option = {'watch_{}'.format(i): e for i, e in enumerate(watch_list)} 

## CREATE A LIST OF MODEL DESCRIPTIONS ACCORDING TO THE TYPE OF WATCH SELECTED: 
## > Read each model HTML link in watch_link_urls. 
## > Search for the terms starting with dib_02 followed by any combination of capital 
## letters, numbers and backslashes. 
## > Insert Tkinter instructions to each result as strings 
## > Append the results to a list called watch_model_description_list. 
    watch_model_description_list = [] 
    watch_model_description_grid_list = [] 
    for num, url in enumerate(watch_link_urls): 
     dennisov_model_html = urlopen(url).read() 
     dennisov_model_html = dennisov_model_html.replace('"', "'") 
     watch_model_description = findall("dib_02'\>([A-Z \/0-9]+)\<", dennisov_model_html) 
     for number, category in enumerate(watch_model_description): 


      watch_model_description = 'category_' + str(loop_count) + ' = Label(window, text = "'+ category +'")' 
      watch_model_description_grid = 'category_' + str(loop_count) + '.grid(padx = 5, pady = 0, row = ' + str(number+3) + ', column = '+ str(num) +')' 
      watch_model_description_list.append(watch_model_description) 
      watch_model_description_grid_list.append(watch_model_description_grid) 
      loop_count += 1 
    model_option = {'model_{}'.format(i):e for i, e in enumerate(watch_model_description_list)} 
    model_grid_option = {'model_grid{}'.format(i):e for i, e in enumerate(watch_model_description_grid_list)} 
    model_grid_option_string = '\n'.join(model_grid_option.values()) 
    model_option_string = '\n'.join(model_option.values()) 
    print watch_model_description_list 
    print watch_model_description_grid_list 
    print model_option_string 
    print model_grid_option_string 

## models_option = {'model_{}'.format(i):e for i, e in enumerate(watch_model_description_list)} 
## models_option_string = '\n'.join(models_option.values()) 
## print models_option_string 

##watch_model_description_list.append(watch_model_description)   


## Create a description for each watch model 

## models_list = [] 
## models_grid_list = [] 
## for number, category in enumerate(watch_model_description_list): 
##  models_grid = 'model_' + str(category) + '.grid(padx = 0, pady = 0, row = ' + str(category) + ', column = '+ str(number) +')' 
##  models_list.append(models) 
##  models_grid_list.append(models_grid) 
##  models_option = {'model_{}'.format(i):e for i, e in enumerate(models_list)} 
## models_option_string = '\n'.join(models_option.values()) 
## models_grid_option = {'model_grid_{}'.format(i):e for i, e in enumerate(models_grid_list)} 
## models_grid_option_string = '\n'.join(models_grid_option.values()) 
## exec(models_option_string) 
## exec(models_grid_option_string) 
## print models_option_string 
## print models_grid_option_string 

## Create a spinbox 
    spinbox_list = [] 
    spinbox_grid_list = [] 
    for number, watch in enumerate(watch_names): 
     spinbox = 'spinbox_' + str(number) + ' = Spinbox(window, width = 3, from_=0, to=10)' 
     spinbox_grid = 'spinbox_' + str(number) + '.grid(padx = 0, pady = 0, row = 9, column = '+ str(number) +')' 
     spinbox_list.append(spinbox) 
     spinbox_grid_list.append(spinbox_grid) 
     spinbox_option = {'spinbox_{}'.format(i):e for i, e in enumerate(spinbox_list)} 
    spinbox_option_string = '\n'.join(spinbox_option.values()) 
    spinbox_grid_option = {'spinbox_grid_{}'.format(i):e for i, e in enumerate(spinbox_grid_list)} 
    spinbox_grid_option_string = '\n'.join(spinbox_grid_option.values()) 
    exec(spinbox_option_string) 
    exec(spinbox_grid_option_string) 

    prices_list = [] 
    prices_grid_list = [] 
    for number, watch in enumerate(watch_prices): 
     prices = 'price_' + str(number) + ' = Label(window, text = "'+ watch +'")' 
     prices_grid = 'price_' + str(number) + '.grid(padx = 5, pady = 0, row = 8, column = '+ str(number) +')' 
     prices_list.append(prices) 
     prices_grid_list.append(prices_grid) 
     prices_option = {'price_{}'.format(i):e for i, e in enumerate(prices_list)} 
     prices_option_string = '\n'.join(prices_option.values()) 
    prices_grid_option = {'price_grid_{}'.format(i):e for i, e in enumerate(prices_grid_list)} 
    prices_grid_option_string = '\n'.join(prices_grid_option.values()) 
    exec(prices_option_string) 
    exec(prices_grid_option_string) 

    names_list = [] 
    names_grid_list = [] 
    for number, watch in enumerate(watch_names): 
     names = 'name_' + str(number) + ' = Label(window, text = "'+ watch +'")' 
     names_grid = 'name_' + str(number) + '.grid(padx = 5, pady = 0, row = 10, column = '+ str(number) +')' 
     names_list.append(names) 
     names_grid_list.append(names_grid) 
     names_option = {'name_{}'.format(i):e for i, e in enumerate(names_list)} 
    print names_list 
    names_option_string = '\n'.join(names_option.values()) 
    names_grid_option = {'name_grid_{}'.format(i):e for i, e in enumerate(names_grid_list)} 
    names_grid_option_string = '\n'.join(names_grid_option.values()) 
    exec(names_option_string) 
    exec(names_grid_option_string) 



## dennisov_model_selection = Canvas(window, width = 400, height = 850, 
##         bg = 'white') 
## dennisov_model_selection.grid(padx = 2, pady = 2, row = 1, 
##        column = 0, rowspan = 15, columnspan = 3) 




## Create dropdown box text 
dennisov_dropdown_text = Label(window, text = "Watch type:", bg = 'White', width = 20) 

## Create the dropdown box for the Dennisov watch types 
dennisov_dropdown_box = Combobox(window, width = 25, 
            values = dennisov_type_list) 

## Create Dennisov type selection button 
dennisov_select_button = Button(window, text = 'Select', command = display_choice, width = 20) 

## Locate elements on grid 
dennisov_dropdown_text.grid(pady = 2, padx = 2, row = 1, columnspan = 9, sticky = 'W') 
dennisov_dropdown_box.grid(pady = 2, padx = 2, row = 1, columnspan = 9, sticky = 'N') 
dennisov_select_button.grid(pady = 2, padx = 2, row = 1, columnspan = 9, sticky = 'E') 




dennisov_file.close() 
window.mainloop() 

回答

1

你可以简单地添加一个计数器变量:

loop_count = 1 
watch_model_description_list = [] 
watch_model_description_grid_list = [] for num, url in enumerate(watch_link_urls): 
    dennisov_model_html = urlopen(url).read() 
    watch_model_description = findall("dib_02'\>([A-Z \/0-9]+)\<", dennisov_model_html) 
    for number, category in enumerate(watch_model_description): 
     watch_model_description = 'category_' + str(loop_count) + ' = Label(window, text = "'+ category +'")' 
     watch_model_description_grid = 'category_' + str(loop_count) + '.grid(padx = 5, pady = 0, row = ' + str(number+3) + ', column = '+ str(num) +')' 
     loop_count += 1 

loop_count将由1每次通过迭代时间增加第二个for回路

+0

回路计数应该在内部for-loop范围。 – schillingt

+0

@schillingt修正:) – TheGirrafish

+0

由于某些原因,诸如+ =之类的许多功能都不适用于我的Python。我运行2.7,并得到错误“loop_count + = 1 UnboundLocalError:本地变量'loop_count'在作业之前引用” – user88720