简体   繁体   中英

Make a list element of multiple types in python

I want to make a list element that takes values from multiple types of variables. I tried to do like this but it gives the error: cannot concatenate 'str' and 'int' objects

name = "John"
age = 12
data = name + age

I want a list like this

data = [('John', 12)]

只需将它们打包成一个元组并创建一个列表:

data = [(name, age)]

You can just to that :D

test = [None]*2

test[0] = "TEST"
test[1] = 25

print(test)

Gives:
['TEST',25]

I don't really see the problem since lists are capable of storing multiple types.

However, since you seem to want a list of names linked to age, you should look up dictionaries.

data = {'John':12 , 'Marie':14}

In this example data is a dictionary, it's like a list but instead of calling items like data[1] you can call data['Marie'] and it will return you Marie's age (in this case).

If you want more information about dictionaries I suggest you look it up.

即使您有更多列表元素,您也可以为您需要的每个项目提供类型,例如:

list = [int(list[0]),float(list[1]), int(list[2]), float(list[3])]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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