簡體   English   中英

我如何利用字典來在兩個不同的數組中存儲多個值

[英]How can I make use of dictionary in order to store multiple values in two different arrays

我想將INFOSYS和RELIANCE的衍生報價的最后交易價格值存儲在兩個不同的列表中。 之后,我希望我的程序從相應的列表中減去兩個最新值,並提供輸出作為值之間的差異。 給定的代碼提供了一個衍生報價的輸出。

如何使用單個代碼從多個列表中為我提供所需的輸出? 我可以利用字典來解決問題嗎?

import requests
import json
import time
from bs4 import BeautifulSoup as bs
import datetime, threading


LTP_arr=[0]
url = 'https://nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuoteFO.jsp?underlying=INFY&instrument=FUTSTK&expiry=27JUN2019&type=-&strike=-'

def ltpwap():
    resp = requests.get(url)
    soup = bs(resp.content, 'lxml')
    data = json.loads(soup.select_one('#responseDiv').text.strip())

    LTP=data['data'][0]['lastPrice']
    n2=float(LTP.replace(',', ''))

    LTP_arr.append(n2)
    LTP1= LTP_arr[-1] - LTP_arr[-2]

    print("Difference between the latest two values of INFY is ",LTP1)
    threading.Timer(1, ltpwap).start()

ltpwap()

產生:

Difference between the latest two values of INFY is 4.

預期結果是:

INFY_list = (729, 730, 731, 732, 733)
RELIANCE_list = (1330, 1331, 1332, 1333, 1334)    

比保留一些列表更好的方法是使生成器以一定的時間間隔從URL產生所需的值。 這是使用time.sleep()實現,但建議使用許多URL來查看asyncio

from bs4 import BeautifulSoup as bs
import json
import requests
from collections import defaultdict
from time import sleep

urls_to_watch = {
    'INFOSYS': 'https://nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuoteFO.jsp?underlying=INFY&instrument=FUTSTK&expiry=27JUN2019&type=-&strike=-',
    'RELIANCE': 'https://nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuoteFO.jsp?underlying=RELIANCE&instrument=FUTSTK&expiry=27JUN2019&type=-&strike=-'
}

def get_values(urls):
    for name, url in urls.items():
        resp = requests.get(url)
        soup = bs(resp.content, 'lxml')
        data = json.loads(soup.select_one('#responseDiv').text.strip())

        LTP=data['data'][0]['lastPrice']
        n2=float(LTP.replace(',', ''))
        yield name, n2

def check_changes(urls):
    last_values = defaultdict(int)
    current_values = {}
    while True:
        current_values = dict(get_values(urls))
        for name in urls.keys():
            if current_values[name] - last_values[name]:
                yield name, current_values[name], last_values[name]
        last_values = current_values
        sleep(1)

for name, current, last in check_changes(urls_to_watch):
    # here you can just print the values, or store current value to list
    # and periodically store it to DB, etc.
    print(name, current, last, current - last)

印刷品:

INFOSYS 750.7 0 750.7
RELIANCE 1284.4 0 1284.4
RELIANCE 1284.8 1284.4 0.3999999999998636
INFOSYS 749.8 750.7 -0.900000000000091
RELIANCE 1285.4 1284.8 0.6000000000001364

...and waits infinitely for any change to occur, then prints it.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM