pythonlist包含
Ⅰ 如何在python中使列表只包含不同的元素
list去重
List=[1,2,3,1,4,2]
New=list(set(List))
結果
New=[1,2,3,4]
可以網路一下,還有其他方法
Ⅱ python List里可以包含tupletuple里可以包含list
可以,但不建議這樣使用。
元組是不可變變數,包含的list無法刪除,只能做元素增加,刪除元素,還有個別方法也無法使用。
Ⅲ python 在列表中查找包含所以某個字元串的項,並保存到一個新的列表
# 文件不很大的話:
def findstrinfile(filename, lookup):
return lookup in open(filename,'rt').read()
# 對付大文件:
def findstrinlargefile(filename, lookup):
with open(filename, 'rt') as handle:
for ln in handle:
if lookup in ln:
return True
else:
return False
Ⅳ python的list中包含tuple,如何修改tuple中的元素
tuple是不變的。應當是生成新的tuple項添加了待輸出的列表中。
根據規則,分別得到兩個List[Tuple],然後合並即可
A = [...]
B = [...]
def b_in_a(b: tuple) ->bool:
....""""判斷b子項是否能與A中某項對應"""
....for a in A:
........if a[0]==b[0] and a[1].startswith(b[1]):
............return True
....return False
def gen_item(a: tuple) -> tuple:
...."""生成輸出項"""
....for b in B:
........if b_in_a:
............return b + (1,)
....return a[:2] + (0,)
def get_excess() -> list:
...."""得到B中不能與A對應的所有項"""
....return list(map(lambda _: _ + (0,),filter(lambda _: !b_in_a(_),B)))
lst_out = list(map(gen_item, A)) + get_excess()
print(lst_out)
Ⅳ python中的list中多個有包含tuple的list,如何將每個list中的tuple的對應元素相加
我用Python3,最後一行稍微改了一下,執行了看,加上了呀
tagged_list=[[('I',0),('feel',0.2),('happy',0.8),('and',0),('excited',0.4),('today',0)],[('I',0),('feel',0),('happy',1),('and',0),('excited',1),('today',0)],[('I',0),('feel',0),('happy',1),('and',0),('excited',1),('today',0)]]
d={}
forword_listintagged_list:
for(word,score)inword_list:
ifwordind:
d[word]=d[word]+int(score)
else:
d[word]=d.setdefault(word,0)+int(score)
print(*map(tuple,d.items()))
執行結果
('and', 0) ('today', 0) ('I', 0) ('feel', 0) ('excited', 2) ('happy', 2)
第三個就是
Ⅵ python語言中如何直接定義包含若干元素的list
大概是這樣:
list=[[Picture('x11'),Picture('x12')...],
[Picture('x21'),Picture('x22')...],
...
]
Ⅶ python中如何判斷list中是否包含某個元素
index方法 表示在list中查找元素的位置。沒有查找到元素會報錯。
count方法 表示在list中查找元素的個數。沒有為0
Ⅷ python包含不同長度的list的一維數組用0填充統一長度
matrix=[[1],
[1,2],
[1,2,3],
[1,2,3,4],
[1,2,3,4,5],
[3,4,5],
[2,3,4,5],
]
#現在需要將矩陣中所有的列表長度對齊到最長的列表的長度5,末尾全部用0填充
max_len=max((len(l)forlinmatrix))
new_matrix=list(map(lambdal:l+[0]*(max_len-len(l)),matrix))
print(new_matrix)
Ⅸ python中list表示什麼
list是python語言中的基本數據類型列表,使用[]表示;列表中元素的類型可以不相同,它支持數字,字元串甚至可以包含列表,如下:
ak = [1, '67',true,[23,45,67]]
Ⅹ python怎麼判斷list是否包含某個元素
a 是你要找的某個元素
b是list
if a in b:
print 'ok'