2018年1月11日 星期四

Python: Test if a variable is a list or tuple or a set

Python: Test if a variable is a list or tuple or a set

Python Basic: Exercise-145 with Solution

Write a Python program to test if a variable is a list or tuple or a set.
Sample Solution :-
#x = ['a', 'b', 'c', 'd']
#x = {'a', 'b', 'c', 'd'}

x = ('tuple', False, 3.2, 1)
if type(x) is list:
    print('x is a list')
elif type(x) is set:
    print('x is a set')
elif type(x) is tuple:
    print('x is a tuple')    
else:
    print('Neither a list or a set or a tuple.')

H = "Hello"

if type(H) is list or type(H) is tuple:
    print("a list or tuple") 
else:

    print("a string")

======== RESTART: F:/Python_APSC/py-ex-basic-145.py ==========
x is a tuple
a string
>>> 


Python 研究-List、Tuple、String、Dict、Set分析

python的基礎資料結構有:列表(list), 元祖(tuple), 字典(dict), 字串(string), 集合(set)

1)列表(list)

列表是Python中最具靈活性的有序集合物件類型,與字串不同的是,列表可以包含任何種類的物件:數字,字串,甚至是其他列表.並且列表都是可變物件,它支持在原處修改的操作.也可以通過指定的索引和分片獲取元素.列表就可元組的可變版本.

定義一個列表使用一對中(方)括號」 [ ] 「.與元組不同的是, 列表有一些內置的函數對列表進行增加,修改和刪除等操作.可以通過list(seq)函數把一個序列類型轉換成一個列表。

  
#定義一個列表
listA = ['a', 'b', 'c', 1, 2]

2)元組(tuple)

Python中的元組(Tuple)類似於Java中的陣列,一旦新增了一個 tuple,就不能以任何方式改變它。這點與Python中的字串類似,所以我們說元組和字串都是不可變的序列.元組也支持索引和分片操作.

定義一個元組使用一對小(圓)括號」 ( ) 「.

#元組和列表十分類似,只不過元組和字串一樣是

#不可變的 即你不能修改元組

  
#定義一個元組
tuple1 = (1, 2, '3', 4, '5')

3)字典(dict)

字典(Dictionary) 是 Python 的內置資料類型之一,它定義了鍵和值之間一對一的關係,但它們是以無序的方式儲存的。 Python 中的 dictionary 像 Java 中的 Hashtable 類的範例。

定義 Dictionary 使用一對大(花)括號」 { } 」
  
# 定義一個字典
# Dictionary 不只是用於存儲字串。Dictionary 的值可以是任意資料類型,
# 包括字串、整數、物件,甚至其它的 dictionary。
# 在單個 dictionary 裡,dictionary 的值並不需要全都是同一資料類型,可以根據需要混用和匹配。
dict1 = {'name' : 'LiuZhichao', 'age' : 24, 'sex' : 'Male'}

4)字串(string)
  
string = "Hello My friend"
>>> print string[0]
H
>>> print string[0:5]
Hello

5)集合(set)

Python的集合(set)和其他語言類似, 是一個無序不重複元素集, 基本功能包括關係測試和消除重複元素. 集合物件還支持union(聯合), intersection(交), difference(差)和sysmmetric difference(對稱差集)等數學運算.由於集合是無序的,所以,sets 不支持 索引, 分片, 或其它類序列(sequence-like)的操作。

集合也存在不可變形式,frozenset為固定集合.
  
#定義一個集合
set1 = {1, 2, 3, 4, 5}






沒有留言:

張貼留言

Node-Red & ModeBus FC=1

Node-Red & ModeBus FC=1 write address=0..7   8bits read address=16..23 8bits  [{"id":"cf7c1253d4d997dd","type&q...