[英]Python: Replacing chars in an array
我在 Python 中有一個關於 arrays 的問題。 所以我必須在數組內部替換彼此相鄰的字符。 例如(假設輸入將是Mike ):
stack = []
word = input("Type Your word here: ")
wordChars = list(word)
for i in range(len(wordChars)):
stack.append(wordChars[i])
print(stack)
result: ['M', 'i', 'k', 'e']
所以,當我有偶數個字符時 - 我需要替換鄰居,所以:
'M' 和 'i' 等等:'iMek'。
奇數個字符但最后一個數字保持不變,所以對於“情人”:“L”和“o”等等; 然后'r'留在最后:'oLevr'。
我知道如何用模查找單詞是偶數還是奇數,但仍然不知道如何替換鄰居。
a = ['L', 'o', 'v', 'e', 'r']
for i in range(0,len(a)-1,2):
a[i], a[i+1] = a[i+1], a[i]
print(a)
您可以編寫一個 function 替換數組中的 2 個索引:
def replace(arr, i, j):
tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
現在您可以在列表中使用 go 並替換每 2 個鄰居:
for i in range(0, len(wordChars) - 1, 2):
replace(wordChars, i, i + 1)
如 DarrylG 所述,在 python 中,您可以通過執行以下操作交換 2 個元素:
arr[i], arr[j] = arr[j], arr[i]
因此,使代碼更簡單:
for i in range(0, len(wordChars) - 1, 2):
arr[i], arr[j] = arr[j], arr[i]
list.pop(0) 的替代方法
def flip(a):
#convert input string to list
lst = list(a)
#initialise output string
out = ''
# if more than 1 element is left, remove the first two elements and invert
while len(lst)>1:
a = lst.pop(0)
b = lst.pop(0)
out = out + b + a
# if list has at least one element, add this one to the output string
if lst:
out = out + lst.pop()
return out
不用想太多,循環(基於你所說的模數)並執行以下操作:
for x in range(0, len(wordChars) % 2, 2):
char_a = stack[i]
char_b = stack[i + 1]
stack[i] = char_b
stack[i + 1] = char_a
這基本上將以 2 為增量在列表中前進,因此每個增量都會交換項目 0 和 1、2 和 3、4 和 5 等。
您可以一次取兩個字母並進行如下迭代:
length = len(stack)
for i in range(0,length,2):
if(i+1 >= length ):
break
temp = stack[i]
stack[i] = stack[i+1]
stack[i+1] = temp
使用此代碼來做到這一點 -
def is_even(stack):
for i in range(0, len(stack), 2):
temp = stack[i]
stack[i] = stack[i+1]
stack[i+1] = temp
return stack
def is_odd(stack):
for i in range(0, len(stack - 1), 2):
temp = stack[i]
stack[i] = stack[i+1]
stack[i+1] = temp
return stack
stack = []
word = input("Type Your word here: ")
wordChars = list(word)
for i in range(len(wordChars)):
stack.append(wordChars[i])
print(stack)
if len(stack) % 2 == 0:
new_stack = is_even(stack)
else:
new_stack = is_odd(stack)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.