相关疑难解决方法(0)

在'for'循环中访问索引?

如何访问索引本身以获取如下列表?

ints = [8, 23, 45, 12, 78]
for i in ints:
    print('item #{} = {}'.format(???, i))
Run Code Online (Sandbox Code Playgroud)

当我使用循环遍历它时for,如何访问循环索引,在这种情况下从1到5?

python loops list

3312
推荐指数
22
解决办法
194万
查看次数

Python字符串格式:%vs. .format

Python 2.6引入了该str.format()方法,其语法与现有%运算符略有不同.哪种情况更好,哪种情况更好?

  1. 以下使用每种方法并具有相同的结果,那么有什么区别?

    #!/usr/bin/python
    sub1 = "python string!"
    sub2 = "an arg"
    
    a = "i am a %s" % sub1
    b = "i am a {0}".format(sub1)
    
    c = "with %(kwarg)s!" % {'kwarg':sub2}
    d = "with {kwarg}!".format(kwarg=sub2)
    
    print a    # "i am a python string!"
    print b    # "i am a python string!"
    print c    # "with an arg!"
    print d    # "with an arg!"
    
    Run Code Online (Sandbox Code Playgroud)
  2. 此外,何时在Python中发生字符串格式化?例如,如果我的日志记录级别设置为HIGH,我仍然会执行以下%操作吗?如果是这样,有没有办法避免这种情况?

    log.debug("some debug info: %s" % some_info)
    
    Run Code Online (Sandbox Code Playgroud)

python performance logging string-formatting

1323
推荐指数
15
解决办法
96万
查看次数

Python字典理解

是否可以在Python中创建字典理解(用于键)?

没有列表推导,你可以使用这样的东西:

l = []
for n in range(1, 11):
    l.append(n)
Run Code Online (Sandbox Code Playgroud)

我们可以将其缩短为列表理解:l = [n for n in range(1, 11)].

但是,假设我想将字典的键设置为相同的值.我可以:

d = {}
for n in range(1, 11):
     d[n] = True # same value for each
Run Code Online (Sandbox Code Playgroud)

我试过这个:

d = {}
d[i for i in range(1, 11)] = True
Run Code Online (Sandbox Code Playgroud)

不过,我得到一个SyntaxErrorfor.

另外(我不需要这部分,但只是想知道),你能否将字典的键设置为一堆不同的值,如下所示:

d = {}
for n in range(1, 11):
    d[n] = n
Run Code Online (Sandbox Code Playgroud)

字典理解是否可以实现?

d = {}
d[i for i in range(1, 11)] = [x for …
Run Code Online (Sandbox Code Playgroud)

python dictionary list-comprehension

367
推荐指数
7
解决办法
33万
查看次数