我有一个大的列表:
def integers(a, b):
return list(range(a, b+1))
numb = integers(1,100)
numbs = []
for i in range(len(numb)):
numbs.append(str(numb[i])) # strings
numbs = ['1','2',....'100']
我试图删除此列表列表中的所有数字。所以我将数字列表作为1到100的字符串:
mylist
如何在numbs
中遍历列表并删除 static func post(image: UIImage, for username: String) {
let imageData = UIImagePNGRepresentation(image)
let base64Image = imageData?.base64EncodedString(options: .lineLength64Characters)
let url = "https://api.imgur.com/3/upload"
let parameters = [
"image": base64Image
]
Alamofire.upload(multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.append(imageData, withName: username, fileName: "\(username).png", mimeType: "image/png")
}
for (key, value) in parameters {
multipartFormData.append((value?.data(using: .utf8))!, withName: key)
}}, to: url, method: .post, headers: ["Authorization": "Client-ID " + Constants.IMGUR_CLIENT_ID],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { response in
print(response) // url nowhere to be found
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
}
中的数字?在这种情况下我可以使用列表理解吗?
答案 0 :(得分:1)
如果数字始终位于子列表
中mylist = [ x[:-1] for x in mylist ]
答案 1 :(得分:0)
mylist = [[item for item in sublist if item not in numbs] for sublist in mylist]
应该可以解决问题。
然而,这不是相当你所问的。实际上没有从mylist
删除任何内容,我们刚刚构建了一个全新的列表并将其重新分配给mylist
。但是,逻辑结果相同。
答案 2 :(得分:0)
如果数字总是在结尾且只有一次,则可以删除最后一项,如:
my_new_list = [x[:-1] for x in mylist]
如果有更多(如果没有订购),你必须循环通过每个元素,在这种情况下你可以使用:
my_new_list = [[elem for elem in x if elem not in integer_list] for x in mylist]
我还建议按如下方式生成整数列表:
integer_list = list(map(str, range(1, 100)))
我希望它有所帮助:)
答案 3 :(得分:0)
您可以使用isdigit
测试每个字符串,看看它是否只是数字,而不是枚举您要过滤掉的所有整数:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
mylist2 = [[x for x in aList if not x.isdigit()] for aList in mylist]
print mylist2
[['pears', 'apples'], ['grapes', 'trees', 'bears']]
答案 4 :(得分:0)
如果您有以下列表:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
numbs = [str(i) for i in range(1, 100)]
使用列表推导删除numbs
[[l for l in ls if l not in numbs] for ls in mylist]
这是删除列表中数字元素的更通用方法
[[l for l in ls if not l.isdigit()] for ls in mylist]