【问题标题】:Python List of element output is discontinuous [duplicate]元素输出的Python列表不连续[重复]
【发布时间】:2020-12-24 05:25:31
【问题描述】:

我知道当python的列表追加元素时,该元素被追加到尾部。我试图输出列表的元素,为什么元素的地址是乱序的?请帮帮我,谢谢!

list = []
list.append(2)
list.append(10)
list.append(3)
print('--append--')
for i in list:
    print('i:{}, id:{}'.format(i,id(i)))

输出是:

--append--
i:2, id:140711739437936
i:10, id:140711739438192
i:3, id:140711739437968

【问题讨论】:

标签: python


【解决方案1】:

id() 函数返回指定对象的唯一 ID。

你需要使用列表的索引

list = []
list.append(2)
list.append(10)
list.append(3)
print('--append--')
for i in list:
    print('i:{}, id:{}'.format(i,list.index(i))) # replace id with list.index

【讨论】:

  • 想你的答案!可能是我没有描述清楚。 id() 函数返回对象在内存中的地址。当我追加元素时,id的值应该有序增加,但是为什么内存地址不能这样做。
  • @small-orange 我想,this concept 会回答你的问题
  • 很想你。
【解决方案2】:

id() 返回对象的标识(唯一整数)...

a=3
print(id(3)) #9752224  

你可以用这个

list = []
list.append(2)
list.append(10)
list.append(3)
print('--append--')
for i in enumerate(list): #enumerate return an enumerate object.if list it [(0,2),(1,10),(2,3)]
    print('i:{}, id:{}'.format(i[1],i[0]))# for getting index number i[0]

【讨论】:

  • 好的,我知道了。很想你
【解决方案3】:

id函数在实际编程中很少使用,通常使用列表索引来处理列表。您的示例将类似于:

mylist = []
mylist.append(2)
mylist.append(10)
mylist.append(3)
print(mylist)

输出:

[2,10, 3]

示例代码:

for x in range(len(mylist)):
        print(x, mylist[x])

输出:

0, 2
1, 10
2, 3

您可以查看网络上不错的 python 教程之一,例如 python 网页上的一个:https://docs.python.org/3/tutorial/

【讨论】:

  • 好的,我知道了。很想你。
猜你喜欢
  • 2020-01-25
  • 1970-01-01
  • 1970-01-01
  • 2019-08-01
  • 2014-01-02
  • 1970-01-01
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
相关资源
最近更新 更多