鱼C论坛

 找回密码
 立即注册
查看: 3190|回复: 2

为什么我的列表是空的

[复制链接]
发表于 2018-10-2 15:47:25 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. temp = int(input("请输入数字:"))
  2. list1 = []
  3. while temp > 0:
  4.     num = temp % 2
  5.     temp//=2
  6.     list1.append(num)
  7. shengyu = len(list1)
  8. str1 = ""
  9. while temp == 0 and shengyu > 1:
  10.     str1 = str1 + str(list1.pop())
  11. print(str1)
  12.    
复制代码

请输入数字:10
Traceback (most recent call last):
  File "C:\Users\945\Desktop\实验\python\十进制转二进制.py", line 10, in <module>
    str1 = str1 + str(list1.pop())
IndexError: pop from empty list
求解谢谢各位大佬
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-10-2 16:13:21 | 显示全部楼层
你取字符串的while循环有问题
  1. temp = int(input("请输入数字:"))
  2. list1 = []
  3. while temp > 0:
  4.     num = temp % 2
  5.     temp//=2
  6.     list1.append(num)

  7. str1 = "0b"
  8. for i in list1[:]:      #这里必须切片复制,不然会出错
  9.     str1 = str1 + str(list1.pop())
  10. print(str1)
  11.    
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-10-2 22:28:59 | 显示全部楼层
for i in list1[:]:      #这里必须切片复制,不然会出错
这句代码没看懂大佬解释一下好么

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-22 14:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表