gpt4 book ai didi

python - 如何利用字典将多个值存储在两个不同的数组中

转载 作者:太空宇宙 更新时间:2023-11-03 20:47:14 24 4
gpt4 key购买 nike

我想将 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.

关于python - 如何利用字典将多个值存储在两个不同的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56506291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com