zip()
# OUTPUT
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
Python
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print 'What is your {0}? It is {1}.'.format(q, a)
Perl6
my @questions = ('name', ' quest', 'favorite color');
my @answers = ("lancelot", "the holy grail", "blue");
for zip(@questions, @answers) -> ($question, $answer) {
say "What is you $question? It is $answer";
}
按照日期字符串排序
給定一個(gè)列表,按照日期字符串進(jìn)行排序:
list = [ {'date': '2010-04-01','people': 1047, 'hits': 4522},
{'date': '2010-04-03', 'people': 617, 'hits': 2582},
{'date': '2010-04-02', 'people': 736, 'hits': 3277}
]
Python
import operator
list = [ {'date': '2010-04-01','people': 1047, 'hits': 4522},
{'date': '2010-04-03', 'people': 617, 'hits': 2582},
{'date': '2010-04-02', 'people': 736, 'hits': 3277}
]
sorted( list, key = operator.itemgetter('date') )
輸出(默認(rèn)是升序):
{'date': '2010-04-01', 'hits': 4522, 'people': 1047},\
{'date': '2010-04-02', 'hits': 3277, 'people': 736}, \
{'date': '2010-04-03', 'hits': 2582, 'people': 617}
Perl6
my @days = Date.new('2005-02-28') .. Date.new('2016-09-22');
my @list = "/perl6/" <<~<< @days;
# 根據(jù)日期進(jìn)行排序
# 降序
my @sorted_des = @list.sort: { $^b.split('/')[2] leg $^a.split('/')[2] }
say .key, "\n", .values for @sorted_des.classy(*.substr(7,7)).sort( { .key } )
# 如果對(duì)想對(duì)生成的散列再做一下加工(計(jì)算每個(gè)月有多少天)
# 就對(duì)生成的散列使用 map, 利用散列的鍵和值重新做一個(gè)映射
say .key, " ", ~.values for @sorted_des.classy(*.substr(7,7)).map( { .key => .value.elems } ).sort( { .key } )
say .key, " ", ~.values for @sorted_des.classy(*.substr(7,7)).map( { ; .key => .value.elems } ).sort( { .key } )
say .key, " ", ~.values for @sorted_des.classy(*.substr(7,7)).map( { .key => .value.elems; } ).sort( { .key } )
# 升序
# @list.sort: { .split('/')[2] };
# @list.sort: { $^a.split('/')[2] leg $^b.split('/')[2] }
統(tǒng)計(jì)字符串各字符出現(xiàn)的次數(shù)
abcdefghijklmnopqrstuvwxyz...abcdefghijklmnopqrstuvwxyz(1千萬個(gè)a-z声搁,不可直接a=1千萬......)中每個(gè)字母的個(gè)數(shù)。要求除了更好的方式(如更加Pythonic的方式),還要計(jì)算越快越好琉朽,并打印出代碼執(zhí)行時(shí)間域帐。
Python
# -*- coding: utf-8 -*-
"""
下面這個(gè)例子就是使用 Counter 模塊統(tǒng)計(jì)一段句子里面所有字符出現(xiàn)次數(shù)
"""
from collections import Counter
s = "sssdfdfwewqewfgfhghghgfhgfh10000000"
c = Counter(s)
# 獲取出現(xiàn)頻率最高的5個(gè)字符
print(c.most_common(5))
# Result:
[(' ', 54), ('e', 32), ('s', 25), ('a', 24), ('t', 24)]
Perl6
my $a = ('a' .. 'z').roll(10000000);
say .key, ' => ', .value for $a.cache.classify(*.Str).map({.key => .value.elems}).sort({-.value});
say now - INIT now;
輸出:(當(dāng)然現(xiàn)在速度不能忍受 180s左右)
q => 385797
a => 385584
o => 385573
e => 385391
c => 385286
p => 385222
...
獲取類的所有方法
Python
for item in dir("hello good people"): print(item)
Perl6
for "hello good people".^methods -> $method { say $method }
調(diào)用類中的每個(gè)方法:
import copy
def all_the_methods(thing):
for meth in dir(thing):
if meth.startswith('_'):
print("Skipping " + meth)
continue
try:
print(meth, ' => ', getattr(copy.copy(thing), meth)())
except Exception as e:
print(Exception, ":", e)
all_the_methods("hello good people")
在 Python 中要將字符串當(dāng)作函數(shù)名 使用時(shí), 請(qǐng)使用 getattr(調(diào)用者, 字符串方法)
妙黍。 具體請(qǐng)參考 通過函數(shù)名的字符串來調(diào)用這個(gè)函數(shù)悴侵。來看看這一段方法的輸出:
Skipping __add__
...
capitalize => Hello good people
islower => True
...
lower => hello good people
split => ['hello', 'good', 'people']
<class 'Exception'> : translate() takes exactly one argument (0 given)
...
Perl6
sub all-the-methods($thing) {
for $thing.^methods -> $method {
say "{$method.name} => {$thing.clone.$method.gist}";
CATCH { default { say "{$method.name} => ERROR" } }
}
}
all-the-methods <this is words>;
all-the-methods "hello little fishies!";
接收一系列方法, 遍歷這些方法并一次性調(diào)用它們。在這里我們做了一次克隆(.clone
), 以使如果它是可變函數(shù)的話我們將在它的一個(gè)副本上工作拭嫁。注意, .clone
不是 深度復(fù)制, 所以它雖然能在我這個(gè)簡(jiǎn)單的字符串例子中工作但是它可能在其它東西上沒有作用可免。.gist
調(diào)用給了我們結(jié)果一個(gè)很好的可打印版本。
我們不用參數(shù)調(diào)用那些方法, 很多方法對(duì)不帶參數(shù)不感冒做粤。所以這兒我們提供了一個(gè) CATCH 塊以打印出通用信息 -- 它在一個(gè)循環(huán)里面所以在捕獲一個(gè)錯(cuò)誤之后它會(huì)跳轉(zhuǎn)到下一個(gè)方法上巴元。
這兒是輸出:
# <this is words>
permutations => ((this is words) (this words is) (is this words) (is words this) (words this is) (words is this))
join => thisiswords
pick => is
roll => words
reverse => (words is this)
rotate => (is words this)
append => ERROR
# "hello little fishies!"
ords => (104 101 108 108 111 32 108 105 116 116 108 101 32 102 105 115 104 105 101 115 33)
wordcase => Hello Little Fishies!
uc => HELLO LITTLE FISHIES!
flip => !seihsif elttil olleh
chop => hello little fishies
contains => ERROR
很多函數(shù)的結(jié)果是 ERROR
, 特別是那些討厭的接收某種參數(shù)的方法。然而, 這些不帶參數(shù)的很多方法能正常工作并返回某些值驮宴。原文All_The_Methods
時(shí)髦的過濾函數(shù)
Python
for f in filter(lambda f: f(-1)>=f(1),
[lambda x:x, lambda x:x**2, lambda x:x**3]):
for x in range(-10, 11):
print x, f(x)
Perl6
for (* ** 1, * ** 2, * ** 3).grep({ $_.(-1) >= $_.(1) }) -> $f {
for -10 .. 10 -> $x {
say "$x: { $f.($x) }"
}
}
Whatever-Star 等價(jià)于:
# Whatever-Star notation
* ** 3
# Pointy-block notation
-> $x { $x ** 3 }
# Subref notation
sub ($x) { $x ** 3 }
上面的例子打印:
-10: 100
-9: 81
-8: 64
-7: 49
-6: 36
-5: 25
-4: 16
-3: 9
-2: 4
-1: 1
0: 0
1: 1
2: 4
3: 9
4: 16
5: 25
6: 36
7: 49
8: 64
9: 81
10: 100