逐元素迭代查询字符串列表

Iterate list on query string element by element

我有一个要单独放入 url 的元素列表,读取下载为 csv 并根据元素命名。然后继续列表中的下一个元素。

例如(编造的地址):

输入list = ['1','2','3'] query_string = f'https://query.number.com/download/{list}&real=true

我想要的输出是df_1 = pd.read_csv('https://query.number.com/download/{1}&real=true') df_2 = ('https://query.number.com/download/{2}&real=true') df_3 = ('https://query.number.com/download/{3}&real=true')

我认为 for 循环是必要的,但不确定如何在移动到当前创建的下一个元素之前完成第一个元素的过程:

query_string = f'https://query.number.com/download/{'1','2','3'} 这会产生错误,尤其是当列表有 100 个元素时

非常感谢任何帮助或资源以了解更多信息,请随时联系,因为我想发展我的编码社区! :)

我不确定我是否明白了。看来你不应该把那个列表放在最开始的 query_string 中。

此外,list是Python中的内置类型,所以不建议在list之后命名任何变量。

ele = ['1', '2', '3']
query_string = 'https://query.number.com/download/{}'
for e in ele:
    do_sth(query_string.format(e))
    output_name = 'df_{}'.format(e)

如果您更喜欢 f 弦:

ele = ['1', '2', '3']
query_string = 'https://query.number.com/download'
for e in ele:
    do_sth(f'{query_string}/{e}')
    output_name = f'df_{e}'
l = [1, 2, 3, 4]
urls = [f'https://query.number.com/download/{i}' for i in l]

这是你想要的吗?

您可以创建一个列表来保存 dfs,并将 csv 读入一个新的 df,然后附加到您的 dfs 列表。我不确定你为什么想要 100 个不同的 dfs。如果您随后想对 dfs 列表中的 dfs 执行某些操作,则可以使用 dfs 列表中 df 的索引保存到文件等。

通常我会有 1 个巨大的 df,并将 1、2、3 输入作为值放在其中一列中。然后你可以根据输入列过滤df。

list_of_dfs = []
giant_df = pd.DataFrame()

input_list = ['1', '2', '3']
for inp in input_list:
    # get the df for this csv
    df = pd.read_csv('https://query.number.com/download/' + inp)
    
    # append to your list of dfs
    list_of_dfs.append(df)

    # or to keep it all in 1 df:
    df['input'] = inp
    giant_df = giant_df.append(df)

# to filter a df with only the input 1
df1 = giant_df[giant_df['input'] == '1']