簡體   English   中英

如何拆分用戶輸入以使其占用數組中的兩個索引位置? (Python)

[英]How do I split up a user input so that it takes up two index places in an array? (Python)

我希望能夠接受用逗號分隔的幾個不同單詞的用戶輸入,然后將它們添加到數組中,以便他們輸入的每個單詞都占用不同的索引值。 這是我為此使用的 function:

array = ["cat","dog","house","car"]
print(array)

def append():#accepts a user input and adds it to the array
item = input("What would you like to append: ")
item = item.lower()
array.append(item)#appends the item variable delcared in the above statement
print ("The list is now: ",array)

目前,這是通過獲取一個用戶輸入,將其更改為小寫,將其添加到數組並打印出來來實現的。 我想擁有它,以便用戶可以輸入:鼠標、馬、山,程序會將這三個項目分別添加到數組中。 目前,它將它們全部加在一起-應該如此。 我已經嘗試了 split() 命令,但是似乎所做的只是將它們作為一件事添加,然后在它們周圍加上方括號。

任何幫助都會很棒。 干杯

您可以使用split功能:

lst = string.split(", ")

它返回一個字符串列表。

輸入:

Apple, Facebook, Amazon

第一:

["Apple", "Facebook", "Amazon"]

更新

獲得列表后,您可以將它們添加到主列表(無論您如何稱呼它):

array += lst

現在array包含這些:

["cat","dog","house","car","Apple", "Facebook", "Amazon"]

像這樣的東西

lst = ["cat","dog","house","car"]

def append():
  item = input("What would you like to append: ")
  lst.extend(item.lower().split(','))
 
print(f'Before: {lst}')
append()
print(f'After: {lst}')

您正在朝着正確的方向思考,因為一個答案指出您可以使用 .split() 方法,我將嘗試再解釋一下。 您可以創建一個項目列表來存儲要附加的字符串列表。 像這樣的東西

```python
item = input("What would you like to append: ")
item_list=item.split(", ")
```

現在你可以使用 for 循環到 append 這個列表你的原始數組。 像這樣的東西。。

```python
for item in item_list:
    item=item.lower()
    array.append(item)
```

完整代碼供參考..

```python
array = ["cat","dog","house","car"]
print(array)

def append():#accepts a user input and adds it to the array
   item = input("What would you like to append: ")
   item_list=item.split(", ")
   for item in item_list:
       item = item.lower()
       array.append(item)     #appends the item variable
print ("The list is now: ",array)```

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM