串列的第一個元素是字串,其余元素是數字。我想在諸如中位數等數字之間執行數學運算,但我無法洗掉第一個元素,即字串,因為我不斷收到此錯誤
AttributeError: 'str' object has no attribute 'pop'
我試過流行,洗掉等
with open('/Users/solidaneziri/Downloads/Data_Exercise_1.txt') as infile:
for line in infile:
alter = line.split()[0]
alter.pop()
statistics.median(alter)
print(Alter)
Alter
28
25
28
26
22
20
25
21
21
25
24
25
26
22
26
20
27
22
22
26
23
20
22
26
24
22
20
20
19
21
19
19
33
23
21
29
21
25
26
19
23
20
25
21
輸入(更改)輸出 = 22.5 中位數
這是檔案 data_exercise 的樣子
Alter Km Geschlecht Raucher Transport Farbe Angst
28 444 m 1 Bahn rot 0
25 50 m 0 Bahn gelb 0
28 8000 m 0 Bahn rot 1
26 9000 m 1 Bahn blau 1
22 4000 m 0 Bahn blau 0
20 0 m 0 Fahrrad grün 0
25 2500 f 0 Fuss rot 0
21 5 m 0 Bahn grün 0
21 200 m 0 Bahn blau 0
25 100 m 0 Bahn blau 0
24 326 m 0 Bahn rot 0
25 5246 m 0 Bahn rot 1
26 20000 m 0 Bahn rot 0
22 10000 m 1 Bahn blau 1
26 400 m 0 Bahn blau 0
20 70 m 0 Bahn rot 0
27 120 m 0 Bahn rot 0
22 0 m 0 Bahn grün 0
22 95 f 0 Fuss rot 0
26 9000 f 0 Fuss gelb 0
23 150 f 1 Fuss rot 1
20 0 m 0 Fuss gelb 0
22 320 m 1 Fuss blau 0
26 400 m 0 Fuss grün 0
24 0 m 0 Fuss blau 0
22 20 f 0 Auto blau 0
20 95 f 0 Auto grün 0
20 100 m 0 Auto grün 1
19 50 m 0 Auto gelb 1
21 5 m 0 Auto blau 1
19 25 m 0 Auto grün 0
19 25 m 0 Auto blau 0
33 230 m 1 Auto blau 0
23 30 m 0 Auto rot 0
21 96 m 1 Auto blau 1
29 156 m 0 Auto grün 0
21 7.5 m 0 Auto grün 0
25 71 f 0 Bahn grün 0
26 218 f 0 Bahn blau 0
19 5632 f 0 Bahn rot 1
23 600 f 0 Bahn blau 0
20 0 f 0 Bahn rot 1
25 2300 f 0 Bahn blau 0
21 200 m 0 Bahn blau 0
uj5u.com熱心網友回復:
只需跳過第一行。 next消耗檔案迭代器的一個元素:
import statistics
with open('/Users/solidaneziri/Downloads/Data_Exercise_1.txt') as infile:
header = next(infile)
data = [int(line.split()[0]) for line in infile]
print(statistics.median(data))
輸出:
22.5
uj5u.com熱心網友回復:
你的錯誤是取了Listat的第一個元素line.split()[0]。
如果每一行都由一個字串后跟數字組成,而您只想洗掉第一個字串,則應該這樣做:
with open('/Users/solidaneziri/Downloads/Data_Exercise_1.txt') as infile:
for line in infile:
alter = line.split()
alter.pop(0)
statistics.median(line)
還要注意,您必須使用 引入List要洗掉的位置的索引pop()。
uj5u.com熱心網友回復:
通過不包括 0 索引來擺脫字串,然后將表示數字的字串轉換為實際的浮點數,以便它們可以在您的計算中使用。
with open('/Users/solidaneziri/Downloads/Data_Exercise_1.txt') as file:
for line in file:
numbers = line.split()[1:]
numbers = map(float, numbers)
statistics.median(numbers)
uj5u.com熱心網友回復:
你可以使用這樣的東西:
import statistics
list_ = []
with open('1.txt') as infile:
for line in infile:
if line.split()[0].isdigit():
list_.append(int(line.split()[0]))
statistics.median(list_)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/328533.html
