【发布时间】:2016-04-27 06:18:10
【问题描述】:
我正在尝试将我的 ruby 脚本转换为 python。我对 python 不是很熟悉,所以我得到了一个TypeError。
打印机.rb
Lease = Struct.new(:property, :renter)
lease_list = []
File.open('input.txt').readlines.each do |line|
p, r = line.split(' - ')
lease_list << Lease.new(p.tr('#', ''), r)
end
# sort by decimal value
lease_list.sort_by { |m| m.property.scan(/\d+/)[0].to_i }.each do |lease|
puts "\##{lease.property} - #{lease.renter}"
end
printer.py
import re
class Lease:
def __init__(self, renter=None, unit=None):
self.renter = renter
self.property = unit
lease_list = []
import sys
lines = open('input.txt', 'r')
for line in lines:
l, m = line.split(' - ')
lease_list.append(Lease(l,m))
lines.close()
print lease_list.sort(key=lambda lease: re.split(r"\d+", lease.property))
python 错误
Traceback (most recent call last): File "printer.py", line 16, in
<module>
print lease_list.sort(key=lambda str: re.split(r"\d+", str)) File "printer.py", line 16, in <lambda>
print lease_list.sort(key=lambda str: re.split(r"\d+", str)) File
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py",
line 171, in split
return _compile(pattern, flags).split(string, maxsplit) TypeError: expected string or buffer
【问题讨论】:
-
这不是语法错误,而是
TypeError。语法错误显示为SyntaxError。是的,有很大的不同。 -
@AvinashRaj 在排序中,我试图找到单位属性的十进制值并按此排序
-
将最后一行的
lease.unit替换为lease.property -
既然你已经修改了代码,这个错误就没有意义了