【问题标题】:Python: Indexing the left side and right side of an assignmentPython:索引分配的左侧和右侧
【发布时间】:2014-10-25 04:39:19
【问题描述】:

我正在尝试做一些简单的事情,如下所示

for k in range(0,2)

outsetk = Reader(FileName='/dir/outset-'+str(k)+'.q')

生成以下内容

outset0 = Reader(FileName='/dir/outset-'+str(0)+'.q')
outset1 = Reader(FileName='/dir/outset-'+str(1)+'.q')
outset2 = Reader(FileName='/dir/outset-'+str(2)+'.q')

其中 Reader 是一些预定义的函数,只有一个输入。我知道作业的右侧是正确的,但我不知道如何做左侧。

【问题讨论】:

  • 使用列表或字典,而不是单独的变量。
  • 如何使用 for 循环生成 list = [outset0,outset1,outset2,...] 的变量列表?
  • 每次循环使用list.append()

标签: python assignment-operator


【解决方案1】:

尝试使用字典来保存结果。像这样的:

outsets = {}

for k in range(0, 3):
    outsets[k] = Reader(FileName='/dir/outset-' + str(k) + '.q')

然后你会像这样访问outset0

outsets[0] # equivalent to your outset0

您还可以执行以下操作来获得示例中提到的相同名称:

outsets = {}
name = 'outset{}'

for k in range(0, 3):
    outsets[name.format(k)] = Reader(FileName='/dir/outset-' + str(k) + '.q')

要访问outset0,您可以使用outsets['outset0']

如果您想改用列表,请尝试以下操作:

outsets = []

for k in range(0, 3):
     outsets.append(Reader(FileName='/dir/outset-' + str(k) + '.q')

然后你会以同样的方式访问outset0

 outsets[0] # equivalent to your outset0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多