【问题标题】:Can you create a list of variables in Python without instantiating the variables?您可以在 Python 中创建变量列表而不实例化变量吗?
【发布时间】:2018-03-28 00:54:47
【问题描述】:

我正在努力使我的代码更简洁。

我想做这样的事情:

gesture_sensor_data = [nod_gyro, nod_acc, swipe_left_gyro, swipe_right_acc, etc.]

我现在有这个:

nod_gyro, nod_acc = fill_gyro_and_acc_data(nod_intervals, merge)
swipe_right_gyro, swipe_right_acc = fill_gyro_and_acc_data(swipe_right_intervals, merge)
swipe_left_gyro, swipe_left_acc = fill_gyro_and_acc_data(swipe_left_intervals, merge)
whats_up_gyro, whats_up_acc = fill_gyro_and_acc_data(whats_up_intervals, merge)

我想通过gesture_sensor_data 运行一个循环。

有没有办法做到这一点?某种结构还是什么?

编辑:我将在此函数中显示我的完整代码以作为上下文。

def generate_gesture_files(i):
    nod_intervals, swipe_left_intervals, swipe_right_intervals, whats_up_intervals = generate_gesture_intervals(i)

    merge = pandas.read_csv(final_user_study_path + "/P" + str(i) + "/DataCollection/data/merge.csv")
    nod_gyro, nod_acc = fill_gyro_and_acc_data(nod_intervals, merge)
    swipe_right_gyro, swipe_right_acc = fill_gyro_and_acc_data(swipe_right_intervals, merge)
    swipe_left_gyro, swipe_left_acc = fill_gyro_and_acc_data(swipe_left_intervals, merge)
    whats_up_gyro, whats_up_acc = fill_gyro_and_acc_data(whats_up_intervals, merge)
    return nod_gyro, nod_acc, swipe_right_gyro, swipe_right_acc, swipe_left_gyro, swipe_right_acc, whats_up_gyro, whats_up_acc

【问题讨论】:

  • 你可以在dict中收集所有这些变量。
  • 键是什么?
  • 这似乎是一种合理的方法;它有什么问题?
  • 我在四行中运行相同的代码,我可以在一个简单的 for 循环中完成。
  • 你不需要那个列表。你可以遍历 itertools.chan([func1(), func2(), func3()])

标签: python list loops variables


【解决方案1】:
itertools.chain([fill_gyro_and_acc_data(i, merge) for i in [
    nod_intervals, swipe_right_intervals, swipe_left_intervals, whats_up_intervals
])

【讨论】:

  • @dirtysocks45:现在好些了吗?
  • 这是否适用于我当前代码中的逻辑?我的 fill_gyro_and_acc_data 返回两个变量。
  • @dirtysocks45:它不返回 2 个变量。它返回一个长度为 2 的可迭代对象。您正在解包它。一个函数总是只返回一个对象。我们正在使用 itertools.chain 合并多个可迭代对象
  • 那么如何将我的局部变量(如nod_gyro)设置为该命令返回的值?
  • nod_gyro、nod_acc、swipe_left_gyro、swipe_right_acc 等 = itertools.chain([...])
【解决方案2】:

你可以改变你的 generate_gesture_intervalsand 使用部分

def generate_gesture_files(i):
  return reduce(lambda x,y:x+y, [fill_gyro_and_acc_data(arg, merge) for arg in generate_gesture_intervals(i)])

【讨论】:

  • 另一种在不减少的情况下使结果变平的方法stackoverflow.com/questions/3204245/…
  • 这里有两个反模式:不要使用reduce 重新发明sum,也不要使用sum 来扁平化列表。
猜你喜欢
  • 1970-01-01
  • 2015-08-01
  • 2020-11-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
  • 2017-12-14
  • 2012-06-02
相关资源
最近更新 更多