如何在Python中从列表中删除字符串



列表的第一个元素是字符串,其余元素是数字。我想在数字之间执行数学运算,比如中位数等但我不能删除第一个元素也就是字符串因为我一直得到这个错误

AttributeError: 'str' object has no attribute 'pop'

我试过pop, remove etc

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中位数

直接跳过第一行。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

您的错误是在line.split()[0]处取List的第一个元素。

如果每行都由后跟数字的字符串组成,并且您只想删除第一个字符串,则应该这样做:

with open('/Users/solidaneziri/Downloads/Data_Exercise_1.txt') as infile:
for line in infile:
alter = line.split()
alter.pop(0)
statistics.median(line)

还要注意,您必须引入您想要用pop()删除的List位置的索引。

通过不包含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)

你可以这样写:

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_)
test_list = ["bad", 2, 4, 6 ,1, 3] 
print ("Original list : " + str(test_list)) 
R = "bad"
while(R in test_list) : 
test_list.remove(R) 
print ("List after removing string " + str(test_list))

my_list = ["one", "two", "three", "four", "five", "six"]打印(my_list)

比如说我想删除1和4

my_list.pop (3)my_list.pop (0)打印(my_list)

#输出将是

("two">

,"three","five","six"]

相关内容

  • 没有找到相关文章

最新更新