python - ATBS:逗号代码
问题描述
我正在尝试解决逗号代码项目以自动化无聊的东西。我遇到了第一个 if 语句的问题。我正在尝试输出字符串:“苹果、香蕉、豆腐和猫”。由于某种原因,它跳过了列表中的第一项。
编辑:本教程不教加入方法,所以我现在不会使用它。我的程序也需要处理所有大小的列表
我认为我应该执行以下操作,但我不断收到 UnboundLocalError: local variable 'first' referenced before assignment
if i < len(list[0:-2]):
first += list[i] + ','
我的代码:
def myList(list):
for i in range(len(list)+1):
if i < len(list[0:-2]):
first = list[i] + ','
elif i == len(list[0:-1]):
second = list[-2]+ ' and '
elif i == len(list[0:]):
last = list[-1]
print(first +second +last)
spam = ['apples', 'bananas', 'tofu', 'cats']
#list index 0 1 2 3
myList(spam)
我的输出是香蕉、豆腐和猫
编辑:我用谷歌搜索的解决方案是 for 循环中的全局变量
def myList(list):
for i in range(len(list)):
if i < len(list[0:-2]):
global first
first += list[i] + ','
elif i == len(list[0:-1]):
global second
second = list[-2]+ ' and '
elif i == len(list[0:]):
global last
last = list[-1]
print(first +second +last)
spam = ['apples', 'bananas', 'tofu', 'cats']
#list index 0 1 2 3
myList(spam)
我的输出现在是香蕉,苹果,香蕉,苹果,香蕉,苹果,香蕉,苹果,香蕉,苹果,香蕉,苹果,香蕉,豆腐和猫
解决方案
我现在正在做这本书(第 2 版),所以我完全是初学者。我对这个练习的回答:
spam = ['apples', 'bananas', 'tofu', 'cats']
def comma_code(source):
source_string = ''
try:
if len(source) == 1:
print(str(source[0]) + '.')
else:
for item in source[:-2]:
source_string = source_string + str(item) + ', '
print(source_string + str(source[-2]) + ' and ' + str(source[-1]) + '.')
except IndexError:
return
comma_code(spam)
结果:
苹果、香蕉、豆腐和猫。
如果列表为空:“ []”
如果列表仅包含 1 项:“[apples]”
苹果。
如果列表是数字:“ [1,2,3,4,5] ”
1、2、3、4 和 5。
我可以在“除了 IndexError”中“打印”一条消息,以创建一个空列表,而不是只捕获错误。我不使用“加入”,因为这本书还没有涵盖(所以我现在不知道是什么)。这个函数只打印结果,所以我制作了另一个版本来将返回值存储在一个变量中供其他函数使用:
spam = ['apples', 'bananas', 'tofu', 'cats']
def comma_code(source):
source_string = ''
try:
if len(source) == 1:
source_string = str(source[0]) + '.'
return source_string
else:
for item in source[:-2]:
source_string = source_string + str(item) + ', '
source_string = source_string + str(source[-2]) + ' and ' + str(source[-1]) + '.'
return source_string
except IndexError:
return
print(comma_code(spam))
我将尝试回答原始消息:
您需要使用调试工具,您会看到为什么缺少第一个单词。我看到的问题在于:
if i < len(list[0:-2]):
不是全局变量问题(程序中的所有变量都是局部变量)。“i”获取值“0”并将“list[0]”添加到变量“first”然后第二次运行“i”获取值 1,但它仍然小于 2,因此它覆盖了“first”变量值为“list[1]”。
推荐阅读
- jenkins - 詹金斯压缩文件
- mule - 如何在 Mule 4 中将大型 CSV 文件写入 SFTP
- go - Grpc Go Generated.pb.go 导入未格式化
- ruby-on-rails - 在 Rails 中-如何从 X 列和总和 Y 列中获取不同的行
- scope - blazor 包含代码块故障 @{} 错误然后 {} 范围错误
- javascript - Vue JS 无限加载在 v-else 中不起作用
- python-3.x - 如果我们要读取此关闭的设备不可用,是否有 PURESNMP 库的功能可以延长 SNMP 查询?
- python - 类型错误:汤= BeautifulStoneSoup(page.text,'lxml')
- ios - 应用程序在后台时,AVAudioPlayer 一段时间后不播放
- r - 如何从 R 中的现有表在 R 中创建新表