Python 在列表中打印特定范围的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41523396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:09:54  来源:igfitidea点击:

Print specific range of numbers in a list

pythonpython-2.7list

提问by user483071

I'm trying to teach self programming. Currently studying python. My resource is MIT OCW

我正在尝试教自编程。目前正在学习蟒蛇。我的资源是 MIT OCW

now, I've just learnt lists and would like to print out the 5th to 9th number in a range (0,10)

现在,我刚刚学习了列表,想打印出范围 (0,10) 中的第 5 到第 9 个数字

The code I've written so far is

到目前为止我写的代码是

new_list = range (0,10)
for i in range (0,10) 
    print "numbers are", new_list [5:9]

I'm getting a Syntax error when I run the code in shell. Error is pointed to the brackets when I use both square are normal brackets.

在 shell 中运行代码时出现语法错误。当我使用方括号是普通括号时,错误指向括号。

Anyone can assist me get the desired output?

任何人都可以帮助我获得所需的输出?

Then also, is that the right use of the "for" function?

那么,这是“for”函数的正确使用吗?

回答by Artemiy

It is simple:

很简单:

print(my_list[5:9])

回答by Frank Schieber

Once again with Python, simplicity reigns supreme. Give this a shot, let me know how it goes:

再次使用 Python,简单性至高无上。试一试,让我知道它是怎么回事:

print([*range(0,10)])

回答by user483071

Following your input, I finally have this code

根据您的输入,我终于有了这个代码

for i in range (0,10)[5:9]:


(indentation) print "the numbers are", i 

回答by Jort de Bokx

You can print the 5th through 9th value by using a for-loop with initial value 5 and final value 9

您可以使用初始值 5 和最终值 9 的 for 循环打印第 5 到第 9 个值

for i in range(5, 9):
    print new_list[i]

This is provided you 'want' to use a for-loop rather than outputting them directly using:

前提是您“想要”使用 for 循环而不是直接使用以下方法输出它们:

print new_list[5:9]

print new_list[5:9]

回答by JMKS

As stated also by others, there is 1 approach which someone achieved already (in answers), and 2 which uses loop to print result:

正如其他人所说,有人已经实现了 1 种方法(在答案中),还有 2 种使用循环来打印结果:

How about code like this:

这样的代码怎么样:

new_list = range (0,10)

for element in new_list[5:9]:
  print "numbers are", element

回答by user483071

I've seen my mistake. The full colon after the "for" function.

我已经看到了我的错误。“for”函数后的完整冒号。

Code now is:

现在的代码是:

new_list = range (0,10)

for i in range (0,10):


(indentation) print "the numbers are", new_list [5:9]

The outcome is

结果是

the numbers are [5,6,7,8]

数字是 [5,6,7,8]

Thanks.

谢谢。