英文:
How to remove a string from an array
问题
我想从数组列表中移除一个字符串。例如,一个数组元素可能是 [290..2, 310.1, 310.0]
。在这种情况下,要移除的字符串是 290..2
。所以基本上我有很多手动输入的数据,我想要排除包含错误输入的整行数据,就像我所示范的例子。是否有现有的函数可以用来解决这个问题?
英文:
I want to remove a string from an array list. For instance one row would be [290..2, 310.1, 310.0]
. In this case the string would be 290..2
. So basically I have a lot of data which is entered manually and I want to omit the entire row which contains a wrong input such as the example I have shown. Are there any existing functions I can use to fix this issue?
答案1
得分: 0
根据您的反馈进行了编辑。听起来您可能有一个包含列表的列表?但根据您的代码,我仍然不确定它是一个列表还是数组。这有帮助吗?
list_1 = [[1, 2, "1..1"], [1, 2, 1], [1, 2, 1], [1, 2, "1..1"], [1, 2, "1..1"], [1, 2, 1]]
list_reversed = reversed(list_1)
len_list_1 = len(list_1)
for ind, sublist in enumerate(list_reversed):
x_t = [isinstance(a, str) for a in sublist]
if any(x_t):
print(f"string here!! - {sublist}")
list_1.pop(len_list_1 - (ind + 1))
else:
print(f"No string here - {sublist}")
print(f"\nResult: {list_1}")
结果如下(即删除包含字符串的子列表):
[[1, 2, 1], [1, 2, 1], [1, 2, 1]]
英文:
Edited based on your feedback. Sounds like you might have a list of lists? Still not sure if it's a list or array based on your code though. Does this help at all?
list_1 = [[1,2,"1..1"], [1,2, 1], [1,2,1], [1,2,"1..1"],[1,2,"1..1"], [1,2, 1]]
list_reversed = reversed(list_1)
len_list_1 = len(list_1)
for ind, sublist in enumerate(list_reversed):
x_t = [isinstance(a, str) for a in sublist ]
if any(x_t):
print(f"string here!! - {sublist}")
list_1.pop(len_list_1-(ind+1))
else:
print(f"No string here - {sublist}")
print(f"\nResult: {list_1}")
Result is as follows (i.e. remove any sublist containing a str):
[[1, 2, 1], [1, 2, 1], [1, 2, 1]]
答案2
得分: 0
Here's the translated code:
我理解你想从列表中筛选出字符串的部分:
list = ["2...7",1,2,3]
list2 = []
for x in list:
if not type(x) == str:
list2.append(x)
else: ## 不是必需的,但我只是为了确认而添加了这个 ##
pass
print (list2)
如果你不想创建第二个列表,你也可以使用这种方法:
list = ["2...7",1,2,3]
for x in list:
if type(x) == str:
list.remove(x)
print (list)
这是输出[对于两种方法都是]:
[1, 2, 3]
<details>
<summary>英文:</summary>
from what i could understand you want to filter out the string from a list
list = ["2...7",1,2,3]
list2 = []
for x in list:
if not type(x) == str:
list2.append(x)
else: ## not required but i just did it for confirmation ##
pass
print (list2)
And if you don't want to create a second list you can also use this method
list = ["2...7",1,2,3]
for x in list:
if type(x) == str:
list.remove(x)
print (list)
this was the **output** [ for both methods ]
> [1, 2, 3]
</details>
# 答案3
**得分**: 0
这个函数将检查列表并返回仅包含有效浮点数值的列表。
<details>
<summary>英文:</summary>
If you are trying to just keep the float values in the list then this might help:
def float_values(lst):
return [val for val in lst if isinstance(val, float)]
This function will check the list and will return a list with only valid float values.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论