Python 如何使用整数从列表中获取字符串?

Python 如何使用整数从列表中获取字符串?,python,list,variables,integer,Python,List,Variables,Integer,如何使用整数从列表中获取字符串 我尝试了这个,但它只是给出了一个错误: list = ['1', '2', '3', '4'] listlength = (len(list) + 1) int1 = 1 int2 = 1 while (int1 < listlength): int2 = list[int1] print(int2) int3 = (int1 + 1) int1 = (int3) Python使用从零开始的索引。列表的索引从0到3,而不是从

如何使用整数从列表中获取字符串

我尝试了这个,但它只是给出了一个错误:

list = ['1', '2', '3', '4']
listlength = (len(list) + 1)
int1 = 1
int2 = 1
while (int1 < listlength):
    int2 = list[int1]
    print(int2)
    int3 = (int1 + 1)
    int1 = (int3)

Python使用从零开始的索引。列表的索引从0到3,而不是从1到4。您的代码假定后者为true,并将
listLength
设置为5,因此当
int=4
时,
int1
为true,但
list[4]
失败,因为该索引不存在

0
处启动
int1
,并使用
listlength=len(list)
从0运行到3

请注意,Python有更好的工具来循环列表。使用仅在值上直接循环:

for int2 in list:
    print(int2)
这要简单得多,也不太可能出错

请注意,使用名称
list
作为变量不是一个好主意,因为这会屏蔽内置的
list
类型。你最好用不同的名字:

values = ['1', '2', '3', '4']
for value in values:
    print(value)
或者,如果必须在
时使用

values = ['1', '2', '3', '4']
values_length = len(values)
index = 0
while index < values_length:
    value = values[index]
    print(value)
    index = index + 1
值=['1','2','3','4']
值\u长度=长度(值)
索引=0
而索引<值\长度:
值=值[索引]
打印(值)
索引=索引+1

您的
int2
ect仍然是长度为1的字符串-您希望实现什么?从
['1','2','3','4']
创建
[1,2,3,4]
?列表是基于0的,列表长度没有多大意义-列表的len()是4,它的索引范围是0,1,2,3,这就是为什么会得到一个IndexError@PatrickArtner:您在哪里看到
int1
被设置为字符串?为什么要将1添加到
listLength
?Python索引从零开始,而不是从1开始。@MartijnPieters拼写错误,Thxy您也可以避免使用Python已经用作变量名的名称-这包括内置名称:-和大多数数据类型,如
列表、集合、冻结集、dict、tuple
…很高兴能提供帮助!如果您觉得它对您有用,请随时使用。:-)<代码>打印(*值,sep=“\n”)
将是另一种go@PatrickArtner:OP几乎肯定需要在循环工作后对值做更多的处理。@PatrickArtner:否则,请参阅以了解如何工作。
values = ['1', '2', '3', '4']
values_length = len(values)
index = 0
while index < values_length:
    value = values[index]
    print(value)
    index = index + 1