リスト内の文字列を変更しようとしました。私はそれぞれの文字列項目を選択するためのループを設定しているが、私はそれを変更することはできません。私はそれがグローバル/ローカルのスコープの問題か、ミュート可能な/不変の型の問題だと思ったが、私はドキュメントを見てきたが、なぜ私はそのコードを使って文字列を修正できないのか分からないたった今。文字列メソッドを使用してリスト内の文字列を変更しました - 切り捨て
小さなプログラムが完了していないが、アイデアは、私たtableData変数を取り、
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
に見えるようにそれを印刷するためにこれは私が結合し、5時間にしてきた問題であり、そのからさ
# This program will take a list of string lists and print a table of the strings.
from copy import deepcopy
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def print_table():
'''This function will take any list of lists and print it in a table format
with evenly spaced columns.'''
# First I wanted to identify the max length of my columns without making changes to my original list
copied_list = deepcopy(tableData)
for copied_innerlist in range(len(copied_list)):
copied_list[copied_innerlist].sort(key=len, reverse=True) # sort each inner list by length
colWidths = [len(copied_innerlist[0]) for copied_innerlist in copied_list] # change the column width variable to reflect the length of longest string in each inner list
# Now that I've stored my columns widths I want to apply them to all the strings without affecting the original
final_list = deepcopy(tuple(tableData))
for item in range(len(final_list)):
for inner_item in final_list[item]:
inner_item = inner_item.rjust(colWidths[item])
'''WHY WONT THIS RJUST METHOD STICK '''
print(final_list)
"""this just looks like that original list! :("""
print_table()
だから、これはループのために項目を変更することがないようにそしてちょうどベストプラクティスですか?私はあなたを正しく理解しているかどうかはわかりません - 私はリストを反復している間にリストを修正していたと思います。私はzip()、map()、リスト内包を教えていなかったので、私はちょっと欲求不満でした。私は機能の開始の近くでリストの理解を使用しましたが、私がそれを見た後でも完全に理解できませんでした –