この答えは、あなたが作成したコードに関するものではありませんが、それをもう一度やろうとした場合の問題への取り組み方に関するものです。
Pythonスタイルガイドでは、 camelCase
の命名規則よりも snake_case
が推奨されているので、ここで使用します。
"リストの値が次のようになっているとします。spam = ['apples'、 'bananas'、 'tofu'、 'cats']
引数としてリスト値を取り、すべての項目をカンマとスペースで区切った文字列を返し、最後の項目の前に挿入する関数を作成します。
ここで実行する必要がある主な機能は何ですか?
簡単に言うと、コードの主な機能は、リスト内の値を取得してこれを文字列に変換することです。
これは、すぐにstring.join()がこれに適した関数になることを示唆しているはずです。
結局のところ、文字列を好きな部分文字列と結合することができます。
', '.join(list_of_strings)
次のような変換が得られます。
['apples', 'bananas', 'tofu', 'cats'] -> 'apples, bananas, tofu, cats'
これでほぼすべての作業が完了しました。 ( 'join()'は0と1の長さのリスト配列を正しく処理するので、必要はありません)
'と'
を挿入するだけです。
A quick analysis of the problem shows that we only need the 'and '
when there are at least two items, so we write a modification to do just that.
We could just add 'and'
in the penultimate location in the list, but we don't want to end up with ['x', 'y'] -> 'x, and, y'
so the simple solution to this is to replace the final input in this case with 'and '
plus the input.
次のいずれかの行でこれを実行できます。
#python 2+:
list_of_strings[-1] = 'and %s' % list_of_strings[-1]
#python 2.6+:
list_of_strings[-1] = 'and {}'.format(list_of_strings[-1])
#python 3.6+:
list_of_strings[-1] = f'and {list_of_strings[-1]}'
これによって入力が変更されないようにするため(他の場所で再利用される可能性があります)、まずそのコピーを作成してください。簡単な方法は、元のものから新しいリストを作成することです。
list_of_strings = list(input_list_of_strings)
これらすべてをまとめると、結果としてかなり単純な関数が得られます。
def comma_code(input_list_of_strings):
list_of_strings = list(input_list_of_strings)
if len(list_of_strings) > 1:
list_of_strings[-1] = f'and {list_of_strings[-1]}'
return ', '.join(list_of_strings)