[英]Check adjacent elements in list
def remove_adjacent(nums):
list1 = []
le = len(nums) # get length of input array (le-1 is the last index)
for idx in range(len(nums)): # iterate through nums using the indices
if idx < le-1: # if before the last element
if nums[idx] != nums[idx +1]: # and if current element is not the same as the next element
list1.append(nums[idx]) # append the current element. Otherwise (elem reoccurs), do not append!
else: # if at last elem of nums
list1.append(nums[idx]) # just append
return list1
我正在學習 Python(目前正在學習 Google 課程)。 任務是:
D. 給定一個數字列表,返回一個列表,其中所有相鄰的 == 元素都已簡化為單個元素,因此 [1, 2, 2, 3] 返回 [1, 2, 3]。 您可以創建一個新列表或修改傳入的列表。
現在我想我設法解決了這個任務,但它看起來很復雜。 此外,我想先學習以最基本的方式編碼,而不是使用大量的模塊導入。 如何使用基本方法集以更優雅的方式解決這個問題? 此外,我希望獲得有關良好編碼風格、習慣、形式等方面的建議和技巧。
你可以用你的清單做一套。 集合只能有一個元素的單個實例。
my_list = [1,2,2,3]
my_set = set(my_list)
print(s)
>>> {1,2,3}
編輯:將集合設為列表。
my_list = list(my_set)
我試着用最簡單的方式來表達。
l = [1,2,2,2,2,3,3]
def removeAdj(num):
prevelem = num[0] -1 ##Assigning prev value one less than first element so that it will not be same as first element
updatedList = [] ## New list
for elem in num:
if elem !=prevelem:
updatedList.append(elem) ## If element not same as previous element append
prevelem = elem ## Assign previous value the current value
return updatedList ## Return updated list
print(removeAdj(l))
您的 function 似乎工作正常,但通過直接迭代元素而不是使用索引可能更“pythonic”。
不使用任何“花哨”的標准庫函數:
def filter_adjacent_dupes(lst):
# make sure to check if `lst` is empty
if not lst:
return lst
# construct a new list that doesn't contain adjacent duplicates
filtered = [lst[0]]
for elem in lst[1:]:
if elem != filtered[-1]:
filtered.append(elem)
return filtered
你也可以考慮把上面的 function 變成一個生成器:
def filter_adjacent_dupes(lst):
# make sure to check if `lst` is empty
if not lst:
return
# yield each valid candidate, skipping duplicates
yield lst[0]
prev_value = lst[0]
for elem in lst[1:]:
if elem != prev_value:
yield elem
prev_value = elem
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.