一个惯用的Python版本的Ruby代码,带有一个测试语句的while循环?

时间:2012-03-13 21:37:14

标签: python ruby

以下代码Ruby代码将迭代源字符串并生成由'。'分隔的累积字的列表。除了最后一个'。'之后的那个字符。

例如,给出一个'Company.Dept.Group.Team'的源字符串,结果将是...... [“Company.Dept.Group”,“Company.Dept”,“公司”]

鉴于Python中的while循环(我相信)将只测试一个表达式而不是如下所示的语句,那么最好如何在惯用Python中编写它?

#ruby
source = 'Company.Dept.Group.Team'
results = []

temp = source.clone
while (i = temp.rindex('.'))  # test statement not supported in Python?
  temp = temp[0...i]
  results << temp
end

p results   # >> ["Company.Dept.Group", "Company.Dept", "Company"]

4 个答案:

答案 0 :(得分:1)

>>> source = 'Company.Dept.Group.Team'
>>> last = []
>>> [last.append(s) or '.'.join(last) for s in source.split('.')[:-1]]
['Company', 'Company.Dept', 'Company.Dept.Group']

答案 1 :(得分:1)

如果你习惯了Python,你会看到列表推导和迭代器/生成器无处不在!

Python可能是

source = 'Company.Dept.Group.Team'

# generate substrings
temp = source.split(".")
results = [".".join(temp[:i+1]) for i,s in enumerate(temp)]

# pop the team (alternatively slice the team out above)
results.pop()

# reverse results
result.reverse()

print result # should yield ["Company.Dept.Group", "Company.Dept", "Company"]

但很可能还有更多惯用的解决方案......

答案 2 :(得分:1)

为了实现这一点,我可能会这样做:

source = 'Company.Dept.Group.Team'
split_source = source.split('.')
results = ['.'.join(split_source[0:x]) for x in xrange(len(split_source) - 1, 0, -1)]
print results

字面翻译更像是:

source = 'Company.Dept.Group.Team'

temp = source
results = []
while True:
    i = temp.rfind('.')
    if i < 0:
        break
    temp = temp[0:i]
    results.append(temp)

print results

或者,如果您愿意:

source = 'Company.Dept.Group.Team'

temp = source
results = []
try:
    while True:
        temp = temp[0:temp.rindex('.')]
        results.append(temp)
except ValueError:
    pass
print results

或者:

source = 'Company.Dept.Group.Team'

temp = source
results = []
i = temp.rfind('.')
while i > 0:
    temp = temp[0:i]
    results.append(temp)
    i = temp.rfind('.')

print results

正如您所指出的那样,您不能将赋值视为表达式这一事实使得这些情况有点不优雅。我认为前一种情况 - 即“真实时” - 比最后一种情况更常见。

有关更多背景信息,此帖子看起来非常不错:http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm

答案 3 :(得分:0)

我愿意

>>> import re
>>> source = 'Company.Dept.Group.Team'
>>> results = [source[:m.start()] for m in re.finditer(r"\.", source)]
>>> results
['Company', 'Company.Dept', 'Company.Dept.Group']

(如果您想要撤销订单,请使用reversed(results)。)

您的代码或多或少的字面翻译将是

source = 'Company.Dept.Group.Team'
results = []
temp = source

while True:
    try:
        i = temp.rindex('.')
        temp = temp[:i]    
        results.append(temp)
    except ValueError:
        break
print(results)