简体   繁体   English

我们如何在下面的代码中使用 List Comprehension?

[英]How do we use List Comprehension for the below code?

This was the given code and I want to use List Comprehension这是给定的代码,我想使用列表理解

    import numpy as np
    
    linear_data = np.array([1,2,3,4,5,6,7,8])
    
    plt.figure()
    xvals = range(len(linear_data))
    plt.bar(xvals, linear_data, width = 0.3)
    
    new_xvals = []

plot another set of bars, adjusting the new xvals to make up for the first set of bars plotted绘制另一组条形图,调整新的 xval 以弥补绘制的第一组条形图

    for item in xvals:
        new_xvals.append(item+0.3)
    
    plt.bar(new_xvals, exponential_data, width = 0.3 ,color='red')

I wrote this line of code but I'm not getting the desired output我写了这行代码,但没有得到想要的输出

    new_xvals = [items for items in xvals new_xvals.append(item+0.3)]

I was getting an error at new_xvals.append(item+0.3) when I used it after "xvals".当我在“xvals”之后使用它时,我在new_xvals.append(item+0.3)处收到错误。 How do I implement this?我该如何实施?

可以使用以下列表理解代码构建列表:

[item+0.3 for item in xvals]

Based on the mistake you're making, I'm guessing you need the more explicit根据你犯的错误,我猜你需要更明确的

    new_xvals = [i+0.3 for i in xvals]

The mistake you're making in your code is trying to append to the list in the interpolation.您在代码中犯的错误是试图在插值中附加到列表中。

Interpolation is creates the list all by itself, so all you need to do is assign it to a variable.插值是自己创建列表,所以你需要做的就是将它分配给一个变量。

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

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