整数のリストがあります-それらをプレーンテキストのランキングに変換するためのライブラリはありますか?IE:1,2,3->「第1、第2、第3」?
7 に答える
pythoninflect
パッケージには、数字を序数に変換するためのメソッドがあります。
import inflect
p = inflect.engine()
for i in range(1,25,5):
print(p.ordinal(i))
表示:
1st
6th
11th
16th
21st
どれくらいの高さで行く予定ですか?(たとえば、「20」よりも高いと予想したことはありますか?)
たぶんあなたはただ必要ですdict
、
nth = {
1: "first",
2: "second",
3: "third",
4: "fourth"
# etc
}
ポイントのためにryvantageの投稿にコメントすることはできませんが、私はpython用に同じコードを書きました:
def appendInt(num):
if num > 9:
secondToLastDigit = str(num)[-2]
if secondToLastDigit == '1':
return 'th'
lastDigit = num % 10
if (lastDigit == 1):
return 'st'
elif (lastDigit == 2):
return 'nd'
elif (lastDigit == 3):
return 'rd'
else:
return 'th'
def appendInt2(num):
value = str(num)
if len(value) > 1:
secondToLastDigit = value[-2]
if secondToLastDigit == '1':
return 'th'
lastDigit = value[-1]
if (lastDigit == '1'):
return 'st'
elif (lastDigit == '2'):
return 'nd'
elif (lastDigit == '3'):
return 'rd'
else:
return 'th'
2つ目は直訳ですが、最初のバリエーションの方がかなり高速であることがわかりました。
2015年8月28日金曜日11:48:13の結果
300000005 function calls in 151.561 seconds
Ordered by: call count, name/file/line
ncalls tottime percall cumtime percall filename:lineno(function)
100000000 6.674 0.000 6.674 0.000 {len}
100000000 43.064 0.000 43.064 0.000 test.py:7(appendInt)
100000000 66.664 0.000 73.339 0.000 test.py:22(appendInt2)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.000 0.000 151.561 151.561 <string>:1(<module>)
1 0.000 0.000 151.561 151.561 test.py:51(main)
1 16.737 16.737 59.801 59.801 test.py:39(test1)
1 18.421 18.421 91.759 91.759 test.py:45(test2)
静脈@HughBothwellがフォローしていたのと同様に、(キー はすでに素晴らしく数値的であるため)を使用しないだけで、次の「ワンライナー」をまとめました。dict
ordinal=lambda x:["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth"][x-1]
これは、12までのすべてのケースをカバーします。より高いもの(数百など)が必要な場合は、おそらくより堅牢なものが必要になります(私が想像する再帰など)。
状況によっては、整数を保持し、「st」、「nd」、「rd」、および「th」を追加すると便利な場合があります。もしそうなら、ここに簡単なアルゴリズムがあります:
注:このアルゴリズムはJavaで記述されています。Pythonを知りません。Pythonで書き直したい人は、私のゲストになってください。
public static String appendInt(int number) {
String value = String.valueOf(number);
if(value.length() > 1) {
// Check for special case: 11 - 13 are all "th".
// So if the second to last digit is 1, it is "th".
char secondToLastDigit = value.charAt(value.length()-2);
if(secondToLastDigit == '1')
return "th";
}
char lastDigit = value.charAt(value.length()-1);
switch(lastDigit) {
case '1':
return "st";
case '2':
return "nd";
case '3':
return "rd";
default:
return "th";
}
}
それで
System.out.println(1 + appendInt(1));
System.out.println(2 + appendInt(2));
System.out.println(3 + appendInt(3));
System.out.println(4 + appendInt(4));
System.out.println(5 + appendInt(5));
System.out.println(11 + appendInt(11));
System.out.println(21 + appendInt(21));
ディスプレイ
1st
2nd
3rd
4th
5th
11th
21st
素晴らしくて簡単な書き直し:
def num_to_ith(num):
"""1 becomes 1st, 2 becomes 2nd, etc."""
value = str(num)
before_last_digit = value[-2]
last_digit = value[-1]
if len(value) > 1 and before_last_digit == '1': return value +'th'
if last_digit == '1': return value + 'st'
if last_digit == '2': return value + 'nd'
if last_digit == '3': return value + 'rd'
return value + 'th'
このための私のコードは、リスト、整数モジュラスを使用して最初の桁を検索し、整数の床除算を使用して、ルール11から13までをチェックします。
def stringify(number):
suffix = ["th","st","nd","rd","th","th","th","th","th","th"]
return str(number) + suffix[number % 10] if str(number // 10)[-1] != 1 else str(number) + "th"
より読みやすい最後の行:
if str(number // 10)[-1] != '1':
return str(number) + suffix[number % 10]
else:
return str(number) + "th"
基本的に、2桁目の1 *をチェックしています。これは、11番目、12番目、13番目のルールブレーカーの可能性を示しています。ルールキーパーの場合、リストは10による除算の余り(モジュラス演算子)によって参照されます。
私はコード効率のテストを行っていません。長さのチェックははるかに読みやすくなっていますが、これは機能します。
*(str(number)[-2]は、入力が1桁の場合、IndexErrorを生成します。整数でフロア除算を使用すると、常に少なくとも1桁になるため、文字列のインデックスは常に-1になります)