for循环不适用于else条件

时间:2019-04-15 08:20:02

标签: python

所以我想对一个列表进行循环计算,但没有成功。我想要一个包含(1+log10(i))的新列表:

    l = [115, 10, 2, 0]

    for i in l:
        l_1 = []
        if i == 0:
            l_1.append(i)
        else:
            l_1.append(1+np.log10(i))

    print(l_1)
    [0]

3 个答案:

答案 0 :(得分:2)

您将在每个循环遍历中创建一个新列表,只需将其取出:

mysqli.allow_local_infile = On

做到这一点的pythonic方法将是一种理解:

l = [115, 10, 2, 0]
l_1 = []
for i in l:
    if i == 0:
        l_1.append(i)
    else:
        l_1.append(1+np.log10(i))

答案 1 :(得分:0)

或者您可以充分利用numpy的优势:

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageSequence

## downloaded from here: 
# https://media.giphy.com/media/uQCxA7u9CEdIA/200w_d.gif
img = Image.open("/path/to/Downloads/brainscan.gif")
frames = np.array([np.array(frame.copy().convert('RGB').getdata(),dtype=np.uint8).reshape(frame.size[1],frame.size[0],3) for frame in ImageSequence.Iterator(img)])

print(np.shape(frames))

frame_index=1

fig,axes=plt.subplots(2,4,figsize=(10,4))
axes[0,0].imshow(frames[frame_index,:,:,0],cmap="Reds_r")
axes[0,1].imshow(frames[frame_index,:,:,1],cmap="Greens_r")
axes[0,2].imshow(frames[frame_index,:,:,2],cmap="Blues_r")
axes[0,3].imshow(frames[frame_index,:,:,:],cmap="viridis")

my_slice= frames[frame_index,50:150,100:120,1]
print(np.shape(my_slice[:]))
frames[frame_index,50:150,100:120,1]=0.1*my_slice

axes[1,0].imshow(frames[frame_index,:,:,0],cmap="Reds_r")
axes[1,1].imshow(frames[frame_index,:,:,1],cmap="Greens_r")
axes[1,2].imshow(frames[frame_index,:,:,2],cmap="Blues_r")
axes[1,3].imshow(frames[frame_index,:,:,:],cmap="viridis")


plt.show()

使用numpy.where清除import numpy as np l = np.array((115, 10, 2, 0)) r = 1 + np.log10(np.where(l != 0, l, 0.1)) # [ 3.06069784 2. 1.30103 0. ] (并用0替换,使得0.1将在{{1}之后产生np.log10(x) = 1 }。

答案 2 :(得分:0)

这里的问题是data = [item.text for item in soup.select('[offerid]')] 给您i中的值而不是索引,因此您只添加一个值,即最后一个。

这是您想要执行的列表理解:

for i in l