Python - Как подсчитать и запомнить количество вхождений в цикле - PullRequest
0 голосов
/ 15 мая 2019

Надеюсь, я смогу как можно яснее объяснить, что я пытаюсь сделать.

Я запускаю цикл while каждые 2 секунды, чтобы получать обновленные значения из 2 разных хранилищ, которые имеют разные значения:

словари выглядят так:

#2 seconds
{'lastUpdateId': 202588846, 'store1': [['24.43000000', '0.00606000'], ['24.42000000', '14.76000000'], ['24.39000000', '2.65760000'], ['24.38000000', '29.59867000'], ['24.35000000', '7.71171000']], 'store2': [['24.47000000', '0.22601000'], ['24.52000000', '0.72000000'], ['24.53000000', '3.28839000'], ['24.54000000', '5.63226000'], ['24.55000000', '20.64052000']]}
#2 seconds
{'lastUpdateId': 202588904, 'store1': [['24.45000000', '0.22596000'], ['24.44000000', '12.84000000'], ['24.43000000', '22.43211000'], ['24.42000000', '5.87234000'], ['24.39000000', '2.65760000']], 'store2': [['24.51000000', '0.00003000'], ['24.52000000', '2.80979000'], ['24.53000000', '17.64938000'], ['24.67000000', '3.41000000'], ['24.68000000', '115.07610000']]}

Теперь я хочу сравнить внутри цикла второе значение из хранилища 1 со вторым значением хранилища 2, я хочу сосчитатьдо 10 раз, если считать 10, то

я хочу, чтобы он продолжал до следующей строки кода, но это то, где я застрял, я не знаю, как это сделать, что я могу сделать для Pythonпомнить счетчик циклов?

вот что я пробовал до сих пор:

import time
def testing():

    stores = {'lastUpdateId': 202588846, 'store1': [['24.43000000', '0.00606000'], ['24.42000000', '14.76000000'], ['24.39000000', '2.65760000'], ['24.38000000', '29.59867000'], ['24.35000000', '7.71171000']], 'store2': [['24.47000000', '0.22601000'], ['24.52000000', '0.72000000'], ['24.53000000', '3.28839000'], ['24.54000000', '5.63226000'], ['24.55000000', '20.64052000']]}

    firststore = [i[1] for i in stores['store1']]

    secondstore = [e[1] for e in stores['store2']]

    offer1 = float(firststore[0]) + float(firststore[1]) + float(firststore[2])


    offer2 = float(secondstore[0]) + float(secondstore[1]) + float(secondstore[2])


    count = 0

    if offer1 > offer2:

        count+=1

        print("This store has the lesser better deal")

        if count == 10:
            print("go ahead and buy")

    if offer2 > offer1:
        count+=1
        print("this other store has the lesser letter deal")

        if count == 10:
            print("go buy this")

i = 0
while True:
    i+=1
    testing()
    time.sleep(2)

может дать мне лучшую идею?может быть с циклом for и добавлением?

Ответы [ 2 ]

2 голосов
/ 15 мая 2019

То, что вы ищете, это генератор. Здесь - отличное объяснение генераторов и как они работают.

Я разбил ваш код сравнения на отдельную функцию генератора, которая назначается объекту генератора offer_comparer, вызывая функцию генератораcompare_offer.Вызов next запускает выполнение функции и возвращает сначала yield.

Затем каждый вызов offer_comparer.send(<params>) отправляет offer1 и offer2 в переменную offers в функции генератора.

Это должно дать вам то, что вы ищете.

import time


def compare_offers():
    count_max = 10
    while True:
        count1 = 0
        count2 = 0
        while count1 < count_max and count2 < count_max:
            offers = yield
            offer1, offer2 = offers[0], offers[1]
            if offer1 > offer2:
                count1 += 1
                print("Store1 has the better deal")
                if count1 == count_max:
                    print("go ahead and buy from store1")
            elif offer2 > offer1:
                count2 += 1
                print("Store2 has the better deal")
                if count2 == count_max:
                    print("go buy this from store2")


offer_comparer = compare_offers()
next(offer_comparer)


def testing():
    stores = {'lastUpdateId': 202588846,
              'store1': [['24.43000000', '0.00606000'],
                         ['24.42000000', '14.76000000'],
                         ['24.39000000', '2.65760000'],
                         ['24.38000000', '29.59867000'],
                         ['24.35000000', '7.71171000']],
              'store2': [['24.47000000', '0.22601000'],
                         ['24.52000000', '0.72000000'],
                         ['24.53000000', '3.28839000'],
                         ['24.54000000', '5.63226000'],
                         ['24.55000000', '20.64052000']]}

    firststore = [float(i[1]) for i in stores['store1']]
    secondstore = [float(e[1]) for e in stores['store2']]

    offer1 = sum(firststore[:3])
    offer2 = sum(secondstore[:3])

    offer_comparer.send((offer1, offer2))


i = 0
while True:
    i += 1
    testing()
    time.sleep(2)
1 голос
/ 15 мая 2019

Вы можете использовать перечисление для подсчета и запоминания количества вхождений в вашем цикле:

for count, item in enumerate(list):
    if (count+1) % 10 == 0 and offer2 > offer1:
        print("go buy this")
    elif (count+1) % 10 == 0 and offer1 > offer2:
        print("go buy this")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...