如何在python中将单个数字转换为单个项目列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29597831/
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-19 04:47:03  来源:igfitidea点击:

How to convert a single number into a single item list in python

pythonlistinteger

提问by latgarf

My solution:

我的解决方案:

>>> i = 2
>>> list1 = []
>>> list1.append(i)
>>> list1
[2]

Is there a more elegant solution?

有没有更优雅的解决方案?

回答by John1024

This is just a special case:

这只是一个特例:

list1 = []

You can put the lists contents between the brackets. For example:

您可以将列表内容放在括号之间。例如:

list1 = [i]

回答by LinkBerest

is it just a single assignment or is this within another construct? if just an assignment:

它只是一个单一的分配还是在另一个结构中?如果只是一个任务:

list1 = [2,] #This is equivalent to list1 = [2], I add the comma out of habit (but either works)
#if construct it depends but this assigns the variable as the list element
list1 = [i] #is fine

回答by Hypaethral

To place something inside of a list, simply wrap it in brackets, like so:

要将某些内容放入列表中,只需将其括在括号中,如下所示:

i = 4
print( [i] )

or

或者

iList = [i]
print( iList )

Run a working example here http://www.codeskulptor.org/#user39_XH1ahy3yu5b6iG0.py

在这里运行一个工作示例http://www.codeskulptor.org/#user39_XH1ahy3yu5b6iG0.py

回答by Hadi K says thanks to Monica

mylist = [i] 

This will create a list called mylist with exactly one element i. This can be extended to create a list with as many values as you want: For example:

这将创建一个名为 mylist 的列表,其中只有一个元素 i。这可以扩展为创建一个包含任意数量值的列表:例如:

mylist = [i1,i2,i3,i4]

This creates a list with four element i1,i2,i3,i4 in that order. This is more efficient that appending each one of the elements to the list.

这将创建一个按顺序包含四个元素 i1,i2,i3,i4 的列表。这比将每个元素附加到列表更有效。

回答by nsaura

As it has already been said, you can write for a single value

如前所述,您可以为单个值编写

    list1 = [i]

This is a "0th order" list comprehension which turns out to be a relevant and powerful python tool.

这是一个“0阶”列表理解,结果证明它是一个相关且强大的python工具。

Check https://docs.python.org/2/tutorial/datastructures.html

检查https://docs.python.org/2/tutorial/datastructures.html