リストのリスト内の値を検索して置換したいと考えています。私の現在のコードは、しかし、私はそれはそれはする必要がありますその後、より複雑だと感じる作品ネストされたリスト内の値を検索して置換する方法
:私はに一緒に答えを石畳ました。これを行うよりエレガントな方法はありますか?
# Create test data- a list of lists which each contain 2 items
numbers = list(range(10))
list_of_lists = [numbers[i:i+2] for i in range(0, len(numbers), 2)]
# Flatten the list of lists
flat_list = [item for sublist in list_of_lists for item in sublist]
# Search for and replace values
modified_list = [-1 if e > 5 else e for e in flat_list]
# Regroup into a list of lists
regrouped_list_of_lists = [modified_list[i:i+2] for i in range(0, len(modified_list), 2)]
これは、おそらく最もPythonicな方法です。それが動作し、読み取り可能な場合は、修正しないでください! – TheLazyScripter
@TheLazyScripter *動作して読み込みが可能な場合は、修正しないでください*この場合はNahです。 –