python - 如何查看两个列表,如果一个列表中的一个条目与另一个列表中的条目匹配,则使用另一个列表,如果不匹配,则继续使用第一个列表?

标签 python list

我正在研究 Python 以及它如何应用于股票交易。

对于特定季度的特定股票,我为其分配了一个值,以帮助我决定是否喜欢该股票。这些值位于名为“B”的列表中。我有另一个列表,其中包含同一股票的所有季度,称为发布日期。

如何创建一个脚本来查看发布列表,如果特定季度的 B 列表中有值,则使用 B 列表中的值,如果没有,则使用值零?

我已经尝试过了

release dates = [...(AAPL, 1, 2010), (AAPL, 2, 2010), (AAPL, 3, 2010), (AAPL, 4, 2010)...]

B = [(AAPL, 1, 2010, 2), (AAPL, 4, 2010, 10)]

output = []
for ticker, quarter, year, in releasedates:
    value_2 = 0
    for ticker_2, quarter_2, year_2, value in B:
        if (ticker_2 == ticker and year_2 == year and quarter_2 == quarter):
        output.append((ticker, quarter, year, value))   
    output.append((ticker, quarter, year, outside, value_2))

但这为我提供了每个日期的两个单独元组中的 B 列表值和 0 值。像这样的事情:

(格式为股票、季度、年份、值)

[... (AAPL, 3, 2015, 10), (苹果公司,3,2015,0) (美国公共(public)图书馆,4,2015,0) ...]

当我真正想要的是这样的时候:

[... (AAPL, 3, 2015, 10), (美国公共(public)图书馆,4,2015,0) ...]

最佳答案

我使用的是示例数据,因为您没有提供您自己的任何示例。如果您使用的字典的键是某种股票,值是某种标志,您可以执行以下操作(O(n) 速度复杂度):

B = {1: True, 4: True}  # Example flags. True being a good stock in this example.
releases = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # Example stocks.
for stock_id in releases:
    if B.get(stock_id):
        # Do Something

否则,在 releases 内循环 B:

B = [(2, True), (4, True)]
releases = [1,2,3,4,5,6,7,8,9,10]
for stock in releases:
    for flag in B:
        if stock == flag[0]:
            # Do Something, you've found a good stock.

更好的是,使用一些面向对象的设计并制作一个库存对象(下面的示例)。

class Stock(object):
   def __init__(self, id, name, price, is_good):
       self.id = id
       self.name = name
       self.price = price
       self.is_good = is_good

这样,您就不需要并行数据容器来比较值;确定好股票的数据完全封装在 Stock 对象本身中。

现在我们可以看到潜在的循环看起来有多干净和高效(不再索引或访问其他容器,只需简单的成员访问)。

for stock in stocks:
   if stock.is_good:
       # enter code here

关于python - 如何查看两个列表,如果一个列表中的一个条目与另一个列表中的条目匹配,则使用另一个列表,如果不匹配,则继续使用第一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41836885/

相关文章:

python - 路径库:无法从 'Sequence' 导入名称 'collections'

python : is there a shortcut for pattern [sth = get_sth() ; if sth: do_a_thing_on(sth)]

python - 如何获取每个打开窗口的名称列表?

python - 在不同的位置绘制轮廓

c - 在链表的头部插入一个新元素并打印元素值

python - 为什么在删除列表时 IPython 管理内存的方式与 CPython 不同?

c# - 你能让一个元素和一个列表中的元素表现得像同一个对象吗?

python - request.POST ['time' ] 必须是 datefield()

c# - 限项 list

javascript - 根据同一 html 表单中的另一个下拉列表填充下拉列表