【问题标题】:How can we create a list and use it dynamically in python我们如何创建一个列表并在python中动态使用它
【发布时间】:2020-07-30 21:20:39
【问题描述】:

我想在 python 中创建一个列表,该列表将包含一个变量,其位置表示 10 个值的列表 位置从 0 到 9 例如 在位置 0 'Abc', 1 'Cde', 2 'Fgh',.... 等等 现在我想在循环中使用列表值递增一

list=['Abc','def','ghi'] # Or this may be an excel file with index and one column having different values

i=0 #has list value 'Abc'
while i<=3:
    a=i
    print('List value at'+i+' equals to',List[i])
i=i+1

输入 数据框

选择索引 0 处的列表值并将其分配给一个对象,然后递增索引直到所有列表值。

需要输出

'List value at 0 equals to Abc'
'List value at 1 equals to def'
'List value at 2 equals to ghi'
'List value at 3 equals to jkl'
'List value at 4 equals to mno'

【问题讨论】:

  • 请用您需要的输出更新您的问题。
  • 您的代码中有一些错误:1. while i&lt;=3 将导致异常,因为您的列表只有三个元素(请记住:python 列表从零开始) 2. 您有 listList 3. 为什么是 a=i ? 4.i=i+1的缩进错误

标签: python list loops while-loop logic


【解决方案1】:

我真的没有得到你的问题,但希望这会有所帮助:

将元素添加到列表

l.append(element)

按位置获取元素

l[0] # Access element from position 0

循环遍历列表元素

for i in l:
    print('Item: {}'.format(i))

按位置循环列表

for i in range(len(l)):
    print('Item: {}'.format(l[i]))

请不要将您的列表命名为 list,它会影响 Python list() 函数。

【讨论】:

  • 您可以在答案中添加切片,因为问题中有 while i&lt;=3:
【解决方案2】:

输入: 列表.xlsx

流程:

k=pd.read_excel('List.xlsx')
m1_list = k.values.tolist()
list = m1_list

i=0
while i < len(list):
    obj= list1[i]
    print(obj)

    i=i+1

输出:

'Abc'
'def'
'ghi'
'jkl'

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 2021-06-16
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多