2018年1月8日 星期一

Python: Generate a list and tuple with comma-separated numbers

Python: Generate a list and tuple with comma-separated numbers

Python Basic: Exercise-6 with Solution

Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.
Sample data: 3, 5, 7, 23
Python list:
list is a container which holds comma separated values (items or elements) between square brackets where items or elements need not all have the same type. In general, we can define a list as an object that contains multiple data items (elements). The contents of a list can be changed during program execution. The size of a list can also change during execution, as elements are added or removed from it.
Python tuple:
tuple is container which holds a series of comma separated values (items or elements) between parentheses such as an (x, y) co-ordinate. Tuples are like lists, except they are immutable (i.e. you cannot change its content once created) and can hold mix data types.
Sample Solution:-
values = input("Input some comma seprated numbers : ")
list = values.split(",")
tuple = tuple(list)
print('List : ',list)
print('Tuple : ',tuple)

=========== RESTART: F:/Python_APSC/py-ex-basic-6.py ==========
Input some comma seprated numbers : 2,21,3,3,45,5
List :  ['2', '21', '3', '3', '45', '5']
Tuple :  ('2', '21', '3', '3', '45', '5')
>>> 
python 串列與tuple非常類似,唯一的差別在於: 
串列list可以修改,而tuple不能修改。 
串列與tuple裡面的成員可以是任何的物件,數字、字串、其他串列或tuple,甚至是辭典、function物件...。它們也可以像字串一樣使用索引、切片來取得其中的成員。


沒有留言:

張貼留言

WOKWI LED + MQTT Node-Red SQLite

WOKWI LED + MQTT Node-Red SQLite const char *mqtt_broker = "broker.mqtt-dashboard.com" ; const char *topic1 = "alex9ufo/e...