我正在使用熊貓從 excel 檔案中獲取串列。
start_path = r'C:\scratch\\'
File = 'test.xlsx'
import pandas as pd
mylist = []
df = pd.read_excel(start_path File, sheet_name='GIS')
mylist = df['Column A'].tolist()
串列:
mylist = ['LB-52/LP-7', 'LB-53/LI-5', 'LB-54/LP-8', 'LB-55', 'LB-56', 'ABC']
然后我的目標是從此串列中創建一個新串列,僅包含以 LB 開頭的元素。因此,新串列將是:
newlist = ['LB-52/LP-7', 'LB-53/LI-5', 'LB-54/LP-8', 'LB-55', 'LB-56']
或者只是從串列中洗掉所有不以“LB”開頭的元素(從而從串列中洗掉 ABC)。
newlist = [str(x for x in mylist if "LB" in x)]
我嘗試了上述方法,這只是吐出:
['<generator object <genexpr> at 0x0000024B5B8F62C8>']
我也嘗試過以下方法:
approved = ['LB']
mylist[:] = [str(x for x in mylist if any(sub in x for sub in approved))]
這將獲得與以前相同的生成器物件訊息。
我覺得這很簡單,但無法弄清楚。
uj5u.com熱心網友回復:
您可以str.startswith
在串列理解中使用:
mylist = ["LB-52/LP-7", "LB-53/LI-5", "LB-54/LP-8", "LB-55", "LB-56", "ABC"]
newlist = [value for value in mylist if value.startswith("LB")]
print(newlist)
印刷:
['LB-52/LP-7', 'LB-53/LI-5', 'LB-54/LP-8', 'LB-55', 'LB-56']
您可以洗掉str()
innewlist = [str(x for x in mylist if "LB" in x)]
但這會留下諸如xxxLBxxx
(LB
在字串中的值)
uj5u.com熱心網友回復:
newlist = [x for x in mylist if x[0:2]=="LB"]
您還可以使用切片并通過切片檢查所需的索引
uj5u.com熱心網友回復:
一般來說,pandas 做同樣的作業往往比 python 快。因此,在“移至”python 之前,您應該嘗試在 pandas 中進行大部分計算或過濾。
mylist = df.loc[df['Column A'].str.startswith("LB"), 'Column A'].tolist()
mylist
>>> ['LB-52/LP-7', 'LB-53/LI-5', 'LB-54/LP-8', 'LB-55', 'LB-56']
uj5u.com熱心網友回復:
mylist = ['LB-52/LP-7', 'LB-53/LI-5', 'LB-54/LP-8', 'LB-55', 'LB-56', 'ABC']
new_list = [*filter(lambda x: x.startswith('LB'), mylist)]
# ['LB-52/LP-7', 'LB-53/LI-5', 'LB-54/LP-8', 'LB-55', 'LB-56']
uj5u.com熱心網友回復:
此代碼有效
newlist = ['LB-52/LP-7', 'LB-53/LI-5', 'LB-54/LP-8', 'LB-55', 'LB-56']
mylist= [ch for ch in newlist if ch[0:2]=="LB"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/473840.html
下一篇:返回列表