python 相当于 perl 的 qw() [英] python equivalent to perl's qw()

查看:68
本文介绍了python 相当于 perl 的 qw()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Perl 中经常这样做:

I do this a lot in Perl:

printf "%8s %8s %8s\n", qw(date price ret);

然而,我能想到的最好的 Python 是

However, the best I can come up with in Python is

print '%8s %8s %8s' % (tuple("date price ret".split()))

我只是想知道是否有更优雅的方法?如果你告诉我就是这样,我很好,没有任何改进.

I'm just wondering if there is a more elegant way of doing it? I'm fine if you tell me that's it and no improvement can be made.

推荐答案

好吧,绝对没有办法完全做到你在 Perl 中可以做的事情,因为 Python 会抱怨未定义的变量名和语法错误(缺少逗号,也许).但我会这样写(在 Python 2.X 中):

Well, there's definitely no way to do exactly what you can do in Perl, because Python will complain about undefined variable names and a syntax error (missing comma, perhaps). But I would write it like this (in Python 2.X):

print '%8s %8s %8s' % ('date', 'price', 'ret')

如果你真的很喜欢 Perl 的语法,我猜你可以像这样定义一个函数 qw:

If you're really attached to Perl's syntax, I guess you could define a function qw like this:

def qw(s):
    return tuple(s.split())

然后你可以写

print '%8s %8s %8s' % qw('date price ret')

除了 qw 的参数上的一对引号外,它基本上类似于 Perl.但我犹豫要不要推荐.至少,不要仅仅因为你想念 Perl 而这样做——它只会让你否认你现在正在使用一种新的编程语言 ;-) 这就像 Pascal 程序员切换到 C 并创建宏的老故事

which is basically Perl-like except for the one pair of quotes on the argument to qw. But I'd hesitate to recommend that. At least, don't do it only because you miss Perl - it only enables your denial that you're working in a new programming language now ;-) It's like the old story about Pascal programmers who switch to C and create macros

#define BEGIN {
#define END   }

这篇关于python 相当于 perl 的 qw()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆