[英]Trouble Comparing Items in List
I have some code that inputs the current market price into a list, and then compares the last two values in that list (in theory).我有一些代码将当前市场价格输入到列表中,然后比较该列表中的最后两个值(理论上)。 When the market goes up, it prints to the terminal
market is up
, when down, market is down
.大盘上涨时打印到终端
market is up
,下跌时market is down
。 However, my code is always printing market is down
(I have checked and the market is indeed up between scrapes).但是,我的代码总是在打印
market is down
(我已经检查过,市场确实在上涨之间)。 What am I doing wrong?我究竟做错了什么? I have a sneaking suspicion I don't understand list indexing.
我偷偷怀疑我不了解列表索引。
Code:代码:
tickers = ['^N225']
for ticker in tickers:
ticker_yahoo = yf.Ticker(ticker)
data = ticker_yahoo.history()
last_quote = data['Close'].iloc[-1]
L = float(last_quote)
M = trunc(L)
f = open('market.txt', 'a')
f.write(str(L))
f.write('\n')
f.write(str(L))
print(M)
list = []
list.append(M)
N = list[-1]
O = list[0]
if N > O:
print("Market is up")
else:
print("Market is down")
time.sleep(10)```
May be I'm missing something,可能是我遗漏了什么,
It looks like you are appending a float (M) to an empty list (list) so list[0] and list[-1] are both M.看起来你正在将一个浮点数 (M) 附加到一个空列表 (list),所以 list[0] 和 list[-1] 都是 M。
If M is a list (?)如果 M 是一个列表(?)
using "append" insert a single element so you generate a list of list with a single list element使用“追加”插入单个元素,以便生成具有单个列表元素的列表列表
list = []
other = [1,2,3,4]
list.append(other) # [[1, 2, 3, 4]]
print(list[0]) # [1,2,3,4]
print(list[-1]) # [1,2,3,4]
# you should prefer
list = []
other = [1,2,3,4]
list.extend(other)
print(list[0]) # 1
print(list[-1]) # 4
# expected ?
print(list[-2]) # 3
simply why not making comparison on M items (if M is a list)只是为什么不对 M 个项目进行比较(如果 M 是一个列表)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.