简体   繁体   English

Python:列表中有多种数据类型

[英]Python: multiple data types in a list

Using: Py3.X使用:Py3.X

Hi, i have a list as shown below, and i want to print it's field individually, May i know how can i store multiple data types into a variable.嗨,我有一个如下所示的列表,我想单独打印它的字段,我可以知道如何将多种数据类型存储到一个变量中。

Failed:失败的:

S = [1, 2, a, b]

NameError: name 'a' is not defined

Success:成功:

T = ['1','2','a','b']
print(T[1])
2

How to make 'S' into the format of 'T' that every field is saved with single quotes.如何将'S'变成'T'的格式,每个字段都用单引号保存。 else how can i use 'S' list without putting those fields under single quotes.否则我如何使用“S”列表而不将这些字段放在单引号下。

required output:所需 output:

print(S[1])
2

When we write:当我们写:

var = 'a'    # This is string 'a'

var will store a reference to the string 'a' . var将存储对string 'a'的引用。

When we write:当我们写:

var = a      # This is variable a

var will store a reference which the variable a is storing. var将存储variable a正在存储的引用。


You can do something like this:你可以这样做:

S = [1, 2, 'a', 'b']    # First two are integers and the last two are strings. 

you either have to define a, or assign it as a string:您要么必须定义 a,要么将其分配为字符串:

a = 3
l = [1,2,a]
print(l)

output: output:

[1, 2, 3]

OR或者

l = [1,2,'a']
print(l)

output: output:

[1, 2, 'a']

your error is because you haven't assigned a value to a您的错误是因为您没有为 a 赋值

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

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