[英]Extract data from a list Python
我有一個字符串列表,我想取它的最后一個“單詞”,解釋:
這是我的代碼:
myList = ["code 53 value 281", "code 53 value 25", ....]
我想只取最后的數字:
myList = ["281", "25", ....]
謝謝你。
讓我們分解你的問題。
所以首先,你有一個字符串列表。 您知道每個字符串都以某種數值結尾,您想將其取出並將其存儲在列表中。 基本上,您想擺脫除最后一個數值之外的所有內容。
為了用代碼編寫它,我們需要在該列表上迭代,用空格字符' '
分割每個字符串,然后從該集合中獲取最后一個單詞,並將其存儲在列表中。
有很多方法可以做到這一點,但最簡單的是列表理解。
myList = ["Hey 123", "Hello 456", "Bye 789"] # we want 123, 456, 789
myNumericList = [x.split(' ')[-1] for x in myList]
# for x in myList is pretty obvious, looks like a normal for loop
# x.split(' ') will split the string by the space, as an example, "Hey 123" would become ["Hey", "123"]
# [-1] gets the last element from the collection
print(myNumericList) # "123", "456", "789"
我不知道你為什么要檢查文本中是否有整數,提取它們,然后將它們轉換回字符串並添加到列表中。 無論如何,您可以使用 .split() 在空格上拆分文本,然后嘗試將拆分的字符串解釋為整數,如下所示:
myList = ["code 53 value 281", "code 53 value 25"]
list = []
for var in myList:
list.append(var.split()[-1])
print(list)
循環遍歷列表,對於列表中第 i 個索引處的特定值,只需選擇最后一個值。
請參閱下面的代碼部分:
ans=[]
for i in myList:
ans.append(i.split(" ")[-1])
print(ans)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.