簡體   English   中英

如何使用python中的循環(for和while循環)創建具有多個數據類型(字符和整數)的列表。

[英]How to create a list with multiple datatypes (characters as well as integers) using loop (both for and while loop) in python .

我正在嘗試使用循環(for和while循環)創建具有多個數據類型(字符以及整數)的列表。

使用while循環的代碼段如下:

my_list=[]
item=0
while item!=5:
    item=int(input("""Enter the number to create the list(To discontinue enter 5): """))
    my_list.append(item)

print("The list created is: ",my_list)
length=len(my_list)

使用for循環的代碼段:-

list=[]
#Creating the list

count=int(input("Set the length of list as 7, Enter 7: "))
for i in range(count):
    item=int(input("Enter the element: "))
    list.append(item)

    if (count-i==2):
        last_item=int(input("Enter the 7th element:"))
        list.append(last_item)
        break

print("\nThe list created is: ",list)

我的代碼只能使用整數或字符串創建列表。 我無法混合數據類型(即整數和字符串都在同一列表中)。 請提出需要在我的代碼中進行哪些修改。

另外,我還想知道一件事,即使用while循環可以中止執行。當列表中有多個數據類型元素時,該如何完成。

my_list=[]
item=0
while item!="5":
    item=raw_input("""Enter the number to create the list(To discontinue enter 5): """)


    if item.isdigit():
          my_list.append(int(item))

    else:
          my_list.append(item)



print("The list created is: ",my_list)

暫無
暫無

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

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