我有一个数组,
months=['January','February','March','April','May','June','July','August','September','October','November','December']
我希望像
这样的字典months = {1:'January', 2:'February',....}
我试过enumerate()
但没有运气。
如何为列表分配序列号到列表?
提前谢谢!
答案 0 :(得分:4)
由于dict()
构造函数直接从键值对构建字典,因此也可以:
dict(enumerate(months, 1))
以下是一些测试,即使这对您的用例并不重要:
timeit dict(enumerate(months, 1))
The slowest run took 10.34 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 1.37 µs per loop
timeit {i:m for i,m in enumerate(months,1)}
The slowest run took 7.77 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 1.28 µs per loop
timeit {i+1:months[i] for i in range(12)}
The slowest run took 5.42 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 1.89 µs per loop
答案 1 :(得分:2)
试试这个。
months=
['January','February','March','April','May','June','July','August','September','October','November','December']
dict = {i+1:months[i] for i in range(12)}
正如评论中所指出的,使用范围(len(月))。由于在这种情况下已知列表的长度,我使用了12。
答案 2 :(得分:2)
尝试使用此类eumerate
强制它以1开头。
months =['January','February','March','April','May','June','July','August','September','October','November','December']
months = {i:m for i,m in enumerate(months,1)}
print months
将产生
{1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'}
答案 3 :(得分:0)
如果你想坚持枚举,你可以这样做:
bias_palette <- colorRampPalette(c("blue", "magenta", "red", "yellow", "white"), bias=2, space="Lab")
spatstat::plot.im(k, col=bias_palette(256), ribbon = FALSE)
输出:
months =['January','February','March','April','May','June','July','August','September','October','November','December']
d_months = {}
for i, month in enumerate(months):
d_months[i+1] = month
print(d_months)
由于枚举从0开始,您需要使用{1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'}
答案 4 :(得分:0)
请试试这个
{i:months[i] for i in range(len(months))}