简体   繁体   English

数组 python || 时间.strftime

[英]array python || time.strftime

i want a print current index of array using:我想要使用以下方法打印数组的当前索引:

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')

But console is close What happen?但是控制台关闭了会发生什么?

I dont think you can pass a string to a list index我认为您不能将字符串传递给列表索引

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

I don't know what does it means that the console is closing without an error.我不知道控制台正在关闭而没有错误是什么意思。

when running you code I get the following, using python 2.7 :运行您的代码时,我使用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

This is caused because the return of time.strftime("%d", time.localtime()) is a string variable.这是因为time.strftime("%d", time.localtime())的返回是一个字符串变量。

The change in your code needs to be:您的代码中的更改需要是:

print(list1[int(a)])

which will transform that string into an integer.它将将该字符串转换为 integer。

do notice that there is a lot of issue you need to take care of:请注意,您需要处理很多问题:

  1. make sure that the number string you assigning to a is valid确保您分配给a的数字字符串有效
  2. make sure you you don't enter an index that does not exist确保您没有输入不存在的索引

Try this instead, i hope it gives you the output you needed!试试这个,我希望它能给你你需要的 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