如何全局声明此Python lis

2024-09-28 01:27:04 发布

您现在位置:Python中文网/ 问答频道 /正文

import concurrent.futures
import urllib.request
import json

myurls = {}
for x in range(1, 15):
    for y in range(1, 87):

        strvar1 = "%s" % (x)
        strvar2 = "%s" % (y)

        with open("C:\\Python33\\NASDAQ Stock Strings\\NASDAQ_Config_File_{}_{}.txt".format(x,y),"r") as f:
            myurls[x,y] = f.read().replace('\n', '')            
            print("myurls_" + str(strvar1) + "_" + str(strvar2) + "=", myurls[x,y])

            def myglob():
                global myurls


            URLS = [myurls2_1_1,myurls2_1_2,myurls2_1_3,myurls2_1_4,myurls2_1_5 ETC>>>ETC >>>]

下面的代码可以正常工作。这个想法是:

  1. 将多个源.txt文件中的多个字符串定义到字典中。你知道吗
  2. 同时将这些多个变量传递给url=[]语句,以便可以使用期货python的模块。你知道吗

Tags: inimporttxtforetcrangeurllibconcurrent
1条回答
网友
1楼 · 发布于 2024-09-28 01:27:04

你说呢

def myglob():
    global myurls

works syntax wise but the list of variables I then want to use i.e. myurls2_1_1, myurls2_1_2 etc are throwing up an error saying that they are not defined.

没错。但是您已经非常接近了:只需按照您定义它们的方式访问它们:作为myurls[1,1]或您如何定义它们。你知道吗

以动态的方式定义变量几乎从来不是一种可行的方法;通常您可以通过任何dict键或列表索引访问来实现这一点。你知道吗

如您现在提供的示例所示,我可以确切地说明您的做法:

myurls = {}
for x in range(1, 15):
    for y in range(1, 87):

        strvar1 = "%s" % (x) # you can omit these.
        strvar2 = "%s" % (y)

        with open("C:\\Python33\\NASDAQ Stock Strings\\NASDAQ_Config_File_{}_{}.txt".format(x,y),"r") as f: # This is NOT the right place to put an application-specific config file.
            myurls[x,y] = f.read().replace('\n', '')            
            print("myurls[%d,%d] = %s" % (x, y, myurls[x,y]))

            def myglob(): # this function is completely pointless.
                global myurls

# Construct your urls list only after you have everything that belongs in it, i. e. on the correct indentation level:
urls = [myurls[1,1], myurls[1,2], myurls[1,3], myurls[1,4], ...]

这是一条路要走。它看起来非常复杂和奇怪,这最后,非常长的一行。你知道吗

但你可以用列表来缩短它:

urls = [myurls[x,y] for x in range(1, 15) for y in range(1, 87)]

但是,你可能会被问到:“为什么不在路上建造呢?”你知道吗

好吧,我们开始吧:

myurls = {}
urls = []
for x in range(1, 15):
    for y in range(1, 87):

        with open("C:\\Python33\\NASDAQ Stock Strings\\NASDAQ_Config_File_{}_{}.txt".format(x,y), "r") as f:
            thisfile = f.read().replace('\n', '')
            myurls[x,y] = thisfile
            urls.append(thisfile)
            print("myurls[%d,%d] = %s" % (x, y, thisfile))

你来了。你知道吗

没有必要一次将它们全部放到列表中,因为这与并行化无关,而并行化似乎只是在稍后才出现。你知道吗

重要的是在并行化开始时有urls。如果这种情况一次发生或一项一项地发生都无关紧要。你知道吗

相关问题 更多 >

    热门问题