附加功能不起作用

时间:2018-02-01 16:06:18

标签: python python-3.x

所以我写了一个混乱的代码部分,但是当我这样做时,我遇到了一个我无法理解的问题:

x = 4
Number = [1 , 2 , 3 , 4 , 5]
List = []
while x <= 0 :
    List.append(Number[x] * 2)
    x -= 1

但问题是:

print(List) ===> []

不是:

print(List) ===> [ 1 , 2 , 3 , 4 , 5]

我还想感谢您的有用建议,请记住我只是Python Starter:D

6 个答案:

答案 0 :(得分:2)

正如@Zack Tarr所提到的,你需要告诉while循环何时开始和结束。 但是,有一种更清晰的迭代方法:

#Only use camel case for class names
numbers = [1, 2, 3, 4, 5]

#Good job avoiding shadowing of "list"
lst = []

for number in numbers:
    lst.append(number*2)

这相当于使用:

numbers = [1, 2, 3, 4, 5]
lst = []
for i in range(len(numbers)):
    number = numbers[i]
    lst.append(number*2)

正如@Christian Dean所提到的,一个更加pythonic的解决方案是使用类似的东西:

lst = [number * 2 for number in numbers]

这个单行程通过迭代工作,就像我们之前一样,并创建一个列表中的所有&#34;数字* 2&#34; s。

Python是一门很棒的语言,祝你好运!

答案 1 :(得分:2)

我不会回答直接问题(其他答案也是如此),但我会就如何调试这样的事情给出建议。简单地抛出一些print语句:

x = 4
Number = [1 , 2 , 3 , 4 , 5]
List = []
print('Before the loop')
while x <= 0 :
    print('Inside loop, x =', x)
    List.append(Number[x] * 2)
    print('Contents of List = ', List)
    x -= 1
print('After the loop')

如果你运行它,你会发现循环中没有任何内容被打印出来,你可能已经知道检查while循环的逻辑。

答案 2 :(得分:1)

正如其他人所提到的,while循环的条件是False。 无论如何,为此目的,while循环不是最好的解决方案,for更好,列表推导是最好的:

List = [i * 2 for i in Number]

答案 3 :(得分:0)

如在推荐中所述,您需要更新while循环。另外,我不会将var命名为const path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { devtool: 'eval', entry: { portal: [ 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/only-dev-server', './src/index.js' ], decoder: [ 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/only-dev-server', 'broadwayjs/Player/Decoder' ], }, output: { path: path.join(__dirname, 'dist', 'assets'), filename: '[name]ReactBundle.js', publicPath: "/" }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), new HtmlWebpackPlugin({ template: './src/index.html', appMountId: 'root', chunks: ['portal'] }) ], devServer: { contentBase: './src', hot: true }, module:{ rules:[ { test:/\.css$/, use: [ {loader: "style-loader"}, {loader: "css-loader"} ] }, { test: /\.js$/, use: {loader: 'babel-loader'}, exclude: [ path.resolve(__dirname, 'node_modules') ] }, { test: /\.jsx?$/, // Match both .js and .jsx files use: {loader: "babel-loader"}, exclude: [ path.resolve(__dirname, 'node_modules') ] }, { test: /\.(jpe?g|png|gif|svg)$/i, use: {loader: "url-loader?name=src/img/[name].[ext]"} } ] } } ,因为它非常接近python List中的预定义单词。

list

答案 4 :(得分:0)

我认为你只需要改变&lt;到&gt;,像这样:

x = 4
Number = [1 , 2 , 3 , 4 , 5]
List = []
while x >= 0 :
    List.append(Number[x] * 2)
    x -= 1
print(List)

#output
[10, 8, 6, 4, 2]

编写当前程序的方式,while循环永远不会开始。初步检查x&lt; = 0是否失败,因为你已经将x定义为4.如果更新检查说:当x &gt; = 0时,循环开始,因为初始条件是的。

答案 5 :(得分:-2)

问题是x开始时大于0,但你的while条件是x <= 0。