繁体   English   中英

数组 python || 时间.strftime

[英]array python || time.strftime

我想要使用以下方法打印数组的当前索引:

import os
import datetime
import time

a = time.strftime("%d", time.localtime())
list1 = ["123", 123, 123, 132, 123, 123, 123, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
print(list1[a])
input('Press ENTER to exit')

但是控制台关闭了会发生什么?

我认为您不能将字符串传递给列表索引

print(list1[a]) # Lists take integers as indices

我不知道控制台正在关闭而没有错误是什么意思。

运行您的代码时,我使用python 2.7得到以下信息:

>>> print(list1[a])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str

这是因为time.strftime("%d", time.localtime())的返回是一个字符串变量。

您的代码中的更改需要是:

print(list1[int(a)])

它将将该字符串转换为 integer。

请注意,您需要处理很多问题:

  1. 确保您分配给a的数字字符串有效
  2. 确保您没有输入不存在的索引

试试这个,我希望它能给你你需要的 output!

a = int(time.strftime("%d", time.localtime()))
list1 = ["123", 123, 123, 132, 123, 123, 123, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
print(list1[a])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM