① 關於python裡面的set,set之後的集合元素是如何讓排列的
集合set中的元素是沒有順序的。
② Python中list和set的區別
List
字面意思就是一個集合,在Python中List中的元素用中括弧[]來表示,可以這樣定義一個List:
L = [12, 'China', 19.998]
可以看到並不要求元素的類型都是一樣的。當然也可以定義一個空的List:
L = []
Python中的List是有序的,所以要訪問List的話顯然要通過序號來訪問,就像是數組的下標一樣,一樣是下標從0開始:
>>> print L[0]
12
千萬不要越界,否則會報錯
>>> print L[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
IndexError: list index out of range
List也可以倒序訪問,通過「倒數第x個」這樣的下標來表示序號,比如-1這個下標就表示倒數第一個元素:
>>> L = [12, 'China', 19.998]
>>> print L[-1]
19.998
-4的話顯然就越界了
>>> print L[-4]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <mole>
print L[-4]
IndexError: list index out of range
>>>
List通過內置的append()方法來添加到尾部,通過insert()方法添加到指定位置(下標從0開始):
>>> L = [12, 'China', 19.998]
>>> L.append('Jack')
>>> print L
[12, 'China', 19.998, 'Jack']
>>> L.insert(1, 3.14)
>>> print L
[12, 3.14, 'China', 19.998, 'Jack']
>>>
注意python中有幾個方法與append類似,但是效果完全不一樣,使用時需根據實際需求選用正確方法
1.append() 向列表尾部追加一個新元素,列表只佔一個索引位,在原有列表上增加
2.extend() 向列表尾部追加一個列表,將列表中的每個元素都追加進來,在原有列表上增加
比如 list1=[1, 2, 3] .list2=[4, 5, 6]
list1.append(list2) 的結果為[1, 2, 3, [4, 5, 6]]
list1.extend(list2) 的結果為[1, 2, 3, 4, 5, 6]
3.+ 直接用+號看上去與用extend()一樣的效果,但是實際上是生成了一個新的列表存這兩個列表的和,只能用在兩個列表相加上
4.+= 效果與extend()一樣,向原列表追加一個新元素,在原有列表上增加
通過pop()刪除最後尾部元素,也可以指定一參數刪除指定位置:
>>> L.pop()
'Jack'
>>> print L
[12, 3.14, 'China', 19.998]
>>> L.pop(0)
12
>>> print L
[3.14, 'China', 19.998]
也可以通過下標進行復制替換
>>> L[1] = 'America'
>>> print L
[3.14, 'America', 19.998]
Set
set也是一組數,無序,內容又不能重復,通過調用set()方法創建:
>>> s = set(['A', 'B', 'C'])
對於訪問一個set的意義就僅僅在於查看某個元素是否在這個集合裡面,注意大小寫敏感:
>>> print 'A' in s
True
>>> print 'D' in s
False
也通過for來遍歷:
s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)])
for x in s:
print x[0],':',x[1]
>>>
Lisa : 85
Adam : 95
Bart : 59
通過add和remove來添加、刪除元素(保持不重復),添加元素時,用set的add()方法
>>> s = set([1, 2, 3])
>>> s.add(4)
>>> print s
set([1, 2, 3, 4])
如果添加的元素已經存在於set中,add()不會報錯,但是不會加進去了:
>>> s = set([1, 2, 3])
>>> s.add(3)
>>> print s
set([1, 2, 3])
刪除set中的元素時,用set的remove()方法:
>>> s = set([1, 2, 3, 4])
>>> s.remove(4)
>>> print s
set([1, 2, 3])
如果刪除的元素不存在set中,remove()會報錯:
>>> s = set([1, 2, 3])
>>> s.remove(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
KeyError: 4
所以如果我們要判斷一個元素是否在一些不同的條件內符合,用set是最好的選擇,下面例子:
months = set(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec',])
x1 = 'Feb'
x2 = 'Sun'
if x1 in months:
print 'x1: ok'
else:
print 'x1: error'
if x2 in months:
print 'x2: ok'
else:
print 'x2: error'
>>>
x1: ok
x2: error
另外,set的計算效率比list高
③ 關於python list index out of range
一般外部輸入的數據都可能存在問題。所以通常在readlines後要做一次處理
for
line
in
file.readlines():
if
not
line.strip():continue
r
=
line.split('\t')
if
len(r)<3:continue
print
r
try:
records.setdefault(int(r[1]),
{})
records[int(r[1])].setdefault(int(r[0]),
{})
records[int(r[1])][int(r[0])]
=
float(r[2])
except
ValueErro:
continue
這樣就避免了空行,欄位數不足,以及類型轉換出錯。
④ python中如何在set中添加元素語句是什麼
myset = set()
myset.add(1)
print(myset) # 輸出 {1},即當前set中包含了一個元素,該元素為整數1
myset.add(2)
myset.add(100.1)
print(myset) # {1, 2, 100.1}
myset.add(1)
print(myset) # {1, 2, 100.1} 由於set中元素具有唯一性,所以重復元素將不會多次被加入set中
⑤ python dataframe multiindex 有幾層
如何建立多重索引
import pandas as PD
df = PD.DataFrame()
df['a'] = list(range(10,30,2))
df['b'] = df['a'] // 10df.index.name = 'id'#drop : boolean, default True Delete columns to be used as the new indexdf = df.set_index([df['b'], df.index], drop=False)12345678
至此建立了一個帶二重索引的dataframe
⑥ python怎麼知道列表中最大的元素是第幾個
l = [1,2,3]
maxnum = max(l)
print(l.index(maxnum))
index函數只會返回列表裡第一個匹配的值,如果最大值在列表裡有多個,則無法全部查詢到
一個冒泡排序的思路,逐一對比,並記住當前最大值的下標,可以得到最大值的多個下標
l = [1,2,3,0,3]
indeiesDict = {}
maxnum = 0
for i in range(len(l)):
if i > 0 :
if l[i] >= l[i-1]:
maxnum = l[i]
index = i
else:
maxnum = l[i-1]
index = i-1
if indeiesDict.get(maxnum):
indeiesDict[maxnum].add(index)
else:
indeiesDict[maxnum] = set([index])
print(maxnum,indeiesDict[maxnum])
⑦ python 問題 reset_index(drop=True
reset_index用來重置索引,因為有時候對dataframe做處理後索引可能是亂的。
drop=True就是把原來的索引index列去掉,重置index。
drop=False就是保留原來的索引,添加重置的index。
兩者的區別就是有沒有把原來的index去掉。
此外還有一個參數:inplace
inplace=False(默認)表示原數組不變,對數據進行修改之後結果給新的數組。
inplace=True表示直接在原數組上對數據進行修改。
(7)pythonsetindex擴展閱讀:
Python在執行時,首先會將.py文件中的源代碼編譯成Python的byte code(位元組碼),然後再由Python Virtual Machine(Python虛擬機)來執行這些編譯好的byte code。這種機制的基本思想跟Java,NET是一致的。然而,Python Virtual Machine與Java或.NET的Virtual Machine不同的是,Python的Virtual Machine是一種更高級的Virtual Machine。
⑧ python3'set'object does not support indexing怎麼辦
錯誤顯示的是「元組」對象不支持索引;
但是列表支持索引;
a={"a","b","c"}#這是元組,不支持索引
a=["a","b","c"]#這是列表,支持索引,只要把花括弧改成方括弧就行
⑨ 關於python裡面的set,set之後的集合元素是如何讓排列的RT,看下面的例...
set是無序集合,python不保證其中元素的次序.列印結果取決於其內部存儲結構和輸出方式.
你打個長的就知道了
>>>
set('012345678910')
set(['1','0','3','2','5','4','7','6','9','8'])
說明它是按類似二維數組的方式保存的,先把重復的元素剔除,然後把元素按21436587的順序存進二維數組
⑩ python 讀取txt,將每行存為list
import pandas as pd
df=pd.read_table('d:/data.txt',sep=":",encoding='gbk',header=None)
df.columns=['a','b']
df['b']=df.b.map(lambda x:x[1:-1].replace("'",'').replace(' ',''))
df1=pd.concat([df.a,df.b.str.split(',',expand=True)],axis=1)
df1=df1.set_index('a')
df1=df1.stack().reset_index().drop('level_1',axis=1)
df1.to_excel('d:/out_data.xlsx',header=None,index=None)