[英]How can I remove character elements from a list?
I am trying to convert a line from a text file into a list.我正在尝试将文本文件中的一行转换为列表。 The contents of the test file are:
测试文件的内容是:
1 2 3 4 fg 1 2 3 4
I have read the contents into a list lst = ['1','2','3','4','f','g'].我已将内容读入列表 lst = ['1','2','3','4','f','g']。 I want to remove 'f' and 'g' (or whatever characters they may be) and convert all the remaining elements to int type.
我想删除 'f' 和 'g' (或它们可能是的任何字符)并将所有剩余元素转换为 int 类型。 How can I achieve this?
我怎样才能做到这一点?
Instead of removing, rather build a new list.与其删除,不如建立一个新列表。 Python is more efficient when just appending items to a list.
仅将项目附加到列表时,Python 效率更高。 Here we try to convert
i
to an int
- if it is convertable then it reads as some base-10 number, with possible + or - sign.在这里,我们尝试将
i
转换为int
- 如果它是可转换的,那么它读取为一些以 10 为底的数字,可能带有 + 或 - 符号。 If it does not match, then int(i)
throws a ValueError
exception which we just ignore.如果它不匹配,那么
int(i)
会抛出一个ValueError
异常,我们只是忽略它。 Those values that were correctly converted will be appended to a new result
list.那些正确转换的值将被附加到一个新的
result
列表中。
result = []
for i in elements:
try:
result.append(int(i))
except ValueError:
pass
This is a good time for a list comprehension.这是列表理解的好时机。 Convert to int only if isnumeric()
仅当 isnumeric() 时才转换为 int
arr = [int(x) for x in arr if x.isnumeric()]
Try checking if each character can be converted into a character:尝试检查每个字符是否可以转换为字符:
arr = ['1', '2', '3', '4', 'f', 'g']
for c, char in enuemrate(arr[:]):
try:
arr[c] = int(char)
except ValueError:
del arr[c]
print(arr)
You can use the built-in Python method isalpha() .您可以使用内置的 Python 方法isalpha() 。 The method returns “True” if all characters in the string are alphabets, Otherwise, it returns “False”.
如果字符串中的所有字符都是字母,则该方法返回“True”,否则返回“False”。 I'm assuming that there are no alpha-numeric elements in your list, and your list contains either digits or alphabets.
我假设您的列表中没有字母数字元素,并且您的列表包含数字或字母。 You could try something like this:
你可以尝试这样的事情:
elements = [1, 2, 3, 4, 'f', 'g']
for element in elements:
if element.isalpha():
elements.remove(element) #Removing the alphabets
#Converting the remaining elements to int
elements = [ int(x) for x in elements ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.