如何在python中以编程方式比较动态变量

2024-04-19 06:06:28 发布

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

我有一个功能,获取和比较2的6个及以上的网站数据。得到两个站点的数据后,我开始整理数据。由于每个网站有不同的格式,我需要他们每个不同的排序。你知道吗

因为我比较了其中的两个,所以我只需要对其中的两个进行排序。为了做到这一点,我需要知道哪个网站是选择第一和第二个。下面我的代码用if和elif对每个站点进行计算。每个网站都添加到字典中,我找到了一个解决方案来编写另一个if和elif语句。你知道吗

我的问题是:如何只执行相关站点的排序代码 不为每个网站使用if和elif对?有没有一个pythonic或编程的方式来做这件事?你知道吗

我的职责是:

def getpairs(xx,yy):
    mydict = {1:"http://1stsite.com", 2:"http://2ndsite.com", ... , 6:"http://6thsite.com" }
    with urllib.request.urlopen(mydict[xx]) as url:
    dataone = json.loads(url.read().decode())
    with urllib.request.urlopen(mydict[yy]) as url:
    datatwo = json.loads(url.read().decode())

    if xx == 1:
        sorted1 = some code to sort 1st website data(dataone list)
        dataxx = sorted1
    elif yy == 1:
        sorted1 =some code to sort 1st website data(datatwo list)
        datayy = sorted1
    if xx == 2:
    ...
    ...
    ...
    if xx == 6:
        sorted6 = some code to sort 6th website data(dataone list)
        dataxx = sorted6
    elif yy == 6:
        sorted6 = some code to sort 6th website data(datatwo list)
        datayy = sorted6
    compared = set(dataxx).intersection(datayy)
    return compared

谢谢你抽出时间


Tags: tourldataif网站codesomewebsite
1条回答
网友
1楼 · 发布于 2024-04-19 06:06:28

您可以使用排序函数创建另一个字典,其索引方式与mydict的索引方式相同,也可以使用url。像这样:

def sorting_function_1(data):
    ...

def sorting_function_2(data):
    ...

def sorting_function_3(data):
    ...

SORTING_FUNCTIONS = {
    1: sorting_function_1,
    2: sorting_function_2,
    3: sorting_function_3,
    4: sorting_function_2,
    5: sorting_function_1,
    ...
}

def fetch_data(url, sorting_function):
    with urllib.request.urlopen(url) as response:
        data = json.loads(response.read().decode())
        sorted_data = sorting_function(data)
        return sorted_data

def getpairs(xx, yy):
    mydict = { ... }
    dataxx = fetch_data(mydict[xx], SORTING_FUNCTIONS[xx])
    datayy = fetch_data(mydict[yy], SORTING_FUNCTIONS[yy])
    ...

我希望这对你有帮助。你知道吗

相关问题 更多 >