【问题标题】:Python: Compare lists, perform operation, create new listPython:比较列表,执行操作,创建新列表
【发布时间】:2018-11-12 04:03:06
【问题描述】:

我目前正在学习 python,但遇到了一个我似乎无法找到解决方案的问题。我希望你们中的一些人可以帮助我。

问题如下:

我有三个列表,每个列表包含 3000 个元素。每个列表的前五个元素如下:

A = [100, 101, 100, 99, 100...] B = [100, 102, 101, 98, 101...] C = [100, 103, 100, 99, 100...]

我需要使用以下规则创建一个名为 D 的新列表:

对于列表 D 的每个 元素,我需要 Python 首先在列表 A、B 和 C 之间选择相同 index 值最低的那个。也就是说,要确定列表 D 的第 0 个元素是什么,Python 首先需要在列表 A、B 和 C 之间选择具有最小元素的那个索引。每当存在多个具有相同最小值的列表时,Python 需要在这些列表之间随机选择。

以List D的第0个元素为例,因为三个引用列表都有相同的第0个元素(即100),Python需要在三者之间随机选择。

假设 Python 随机选择列表 B。然后,为了确定列表 D 的第 0 个元素,python 将列表 B 的最后一个元素除以它的第 0 个元素。假设列表 B 的最后一个元素是 130。在这种情况下,列表 D 的第 0 个元素将是 1.3。

继续,对于列表 D 的 index=1 元素,Python 将立即选择列表 A,因为它具有最低的 index=1 元素。然后,python 将列表 A 的最后一个元素除以列表 A 的 index=1 元素。假设它是 145。在这种情况下,列表 D 的 index=1 元素将是 145 / 101 = 1.4356

最后,列表 D 也会有 3000 个元素。

有谁知道如何编写代码来解决这个问题?

谢谢。

【问题讨论】:

标签: python list


【解决方案1】:

我认为投反对票是有道理的,因为您根本没有提供任何代码来向我们展示您到目前为止所做的尝试,以便我们知道您的代码在哪里卡住了。另外我认为您编写要求的方式有点令人困惑(0eth 有时可能意味着 nth?)。无论如何,这并不难做到——您只需要zipmin、列表理解和random.choice,您就可以使用n 列表:

from random import choice

a = [100, 101, 100, 99, 100, 110]
b = [100, 102, 101, 98, 101, 130]
c = [100, 103, 100, 99, 100, 120]

# In order to work properly with indexes 
# we should rely on a list of lists
lists = [a, b, c]
# Collect the last value of each sublist in lists
last_values = [sublist[-1] for sublist in lists]
# Your d list
result = []

# zip combines each element from each given list on the same index
# splat the sublists with * (keeps the proper order of sublists)
for zipped in zip(*lists):
  # min selects the lowest value in the zipped values
  lowest = min(zipped)
  # find all occurences of the lowest value within zipped values
  indexes = [i for i, v in enumerate(zipped) if v == lowest]
  # pick a random index (len(indexes) doesn't matter)
  random_index = choice(indexes)
  # Divide the last value in the picked list with the lowest value
  value = last_values[random_index] / lowest
  # And add to result
  result.append(value)

print(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多