包含字符串的打印列表

时间:2019-08-19 17:17:32

标签: python-3.x

我正在尝试存储包含某些名称的字符串变量,我想将相应的变量存储在列表中并打印出来,但是无法打印存储在变量中的值。

name='vsb','siva','anand','soubhik'  #variable containg some names

lis=['name'] # storing the variable in a list

for x in lis:

 print(x) #printing the list using loops

图片:

enter image description here

2 个答案:

答案 0 :(得分:0)

也许是字典?试试这个

variable_1 = "aa"
variable_2 = "bb"
lis = {}
lis['name1'] = variable_1   
lis['name2'] = variable_2

for i in lis:
    print(i)
    print(lis[i])

答案 1 :(得分:0)

您的name变量实际上是一个元组

元组声明示例:

tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"

列表声明示例:

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

为了更好地理解,您应该阅读The Python Standard Library或阅读教程。

对于您的问题,也许字典就是解决方案:

# A tuple is a sequence of immutable Python objects
name='vsb','siva','anand','soubhik'

print('Tuple: ' + str(name)) # ('vsb', 'siva', 'anand', 'soubhik')

# This is a list containing one element: 'name'
lis=['name']

print('List: ' + str(lis)) # ['name']

# Dictionry with key 'name' and vlue ('vsb','siva','anand','soubhik')
dictionary={'name':name}

print('Dictionary: ' + str(dictionary))

print('Dictionary elements:')
print(dictionary['name'])


print('Tuple elements:')
for x in name:
 print(x)

print('List elements:')
for x in lis:
 print(x)

输出

Tuple: ('vsb', 'siva', 'anand', 'soubhik')
List: ['name']
Dictionary: {'name': ('vsb', 'siva', 'anand', 'soubhik')}
Dictionary elements:
('vsb', 'siva', 'anand', 'soubhik')
Tuple elements:
vsb
siva
anand
soubhik
List elements:
name
相关问题