filter,map并且reduce在Python 2中完美地工作.这是一个例子:
>>> def f(x):
return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x):
return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def add(x,y):
return x+y
>>> reduce(add, range(1, 11))
55
Run Code Online (Sandbox Code Playgroud)
但是在Python 3中,我收到以下输出:
>>> filter(f, range(2, 25))
<filter object at 0x0000000002C14908>
>>> map(cube, range(1, 11))
<map object at 0x0000000002C82B70> …Run Code Online (Sandbox Code Playgroud) 我有一个包含空列表的列表:
list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
Run Code Online (Sandbox Code Playgroud)
如何删除空列表以便我得到:
list2 = ['text', 'text2', 'moreText']
Run Code Online (Sandbox Code Playgroud)
我尝试了list.remove(''),但这不起作用.
在Python IDLE 3.5.0 shell中工作.根据我对内置"过滤器"函数的理解,它会返回列表,元组或字符串,具体取决于您传入的内容.那么,为什么下面的第一个分配工作,而不是第二个('>>>只是交互式Python提示)
>>> def greetings():
return "hello"
>>> hesaid = greetings()
>>> print(hesaid)
hello
>>>
>>> shesaid = filter(greetings(), ["hello", "goodbye"])
>>> print(shesaid)
<filter object at 0x02B8E410>
Run Code Online (Sandbox Code Playgroud) 我想使用正则表达式过滤python中的字符串列表.在以下情况中,仅保留扩展名为".npy"的文件.
代码不起作用:
import re
files = [ '/a/b/c/la_seg_x005_y003.png',
'/a/b/c/la_seg_x005_y003.npy',
'/a/b/c/la_seg_x004_y003.png',
'/a/b/c/la_seg_x004_y003.npy',
'/a/b/c/la_seg_x003_y003.png',
'/a/b/c/la_seg_x003_y003.npy', ]
regex = re.compile(r'_x\d+_y\d+\.npy')
selected_files = filter(regex.match, files)
print(selected_files)
Run Code Online (Sandbox Code Playgroud)
同样的正则表达式在Ruby中适用于我:
selected = files.select { |f| f =~ /_x\d+_y\d+\.npy/ }
Run Code Online (Sandbox Code Playgroud)
Python代码有什么问题?
我试图在flask-python中创建一个简单的post api,但是我收到了这个错误:
TypeError: list object is not an iterator
Run Code Online (Sandbox Code Playgroud)
但当我修改我的代码似乎很好可能是什么问题.
我的功能特别有问题:
def post(self,name):
#return {'message': name}
item = next(filter(lambda x: x['name'] == name, items), None)
if item:
return {'message':"An item with name '{}' already exixts. ".format(name)},400
data = request.get_json()
item = {'name': name, 'price':data['price']}
items.append(item)
return item, 201
Run Code Online (Sandbox Code Playgroud)
当我尝试在邮递员上发布某些内容时,我收到此logcat 错误:
[2018-06-07 10:41:02,849] ERROR in app: Exception on /item/test [POST]
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line …Run Code Online (Sandbox Code Playgroud) 什么是正确的过滤器,所以我将包含[(7,10),(9,20)]
>>> l=[(0,5),(7,10),(9,20),(18,22)]
>>> l=filter(lambda x: x[0]>6 and x[1]<21, l)
>>> l
<filter object at 0x7fb2349829e8>
>>>
Run Code Online (Sandbox Code Playgroud)
我得到一个"过滤器对象",而不是原始列表中的两个中间元组的列表.
由于双重条件,我无法找到如何将此函数写为lambda:
def f(e):
if not isinstance(e,list):
if e >10:
return e
else:
return filter(None,[f(y) for y in e])
my_list=[[1], [2,[3,12, [4,11,12]]], [5,6,13,14],[15]]
>>> f(my_list)
[[[12, [11, 12]]], [13, 14], [15]]
Run Code Online (Sandbox Code Playgroud)
另外,编写这样一个过滤任意嵌套列表的函数的pythonic方法是什么?
我有两个单词,一个是用户输入字符串,另一个是从文本文件中随机选择的单词.我想返回两个stings中相等的计数值并共享相同的字符串索引.例如,word1 ='bleed',word2 = slice:similar = 1.
word1 = 'frog'
word2 = 'friend'
correct = 0
if len(word1) > len(word2):
for i in range(len(word2)):
if word1[i] == word2[i]:
correct =+ 1
else:
correct == 0
else:
for i in range(len(word1)):
if word1[i] == word2[i]:
correct =+ 1
else:
correct == 0
Run Code Online (Sandbox Code Playgroud)
我是编程的新手,不幸的是我的尝试最大限度地输出了正确= 1.对于我在示例青蛙和朋友中使用的单词我希望看到正确= 2,我的代码产生正确= 1.我如何添加到正确,超过1?谢谢
colorramps = re.split("#ramp\[([0-9a-fA-F]{6})\](.+?)#rampend\[([0-9a-fA-F]{6})\]", message)
colorramps.reverse()
if len(colorramps) > 1:
starttext = colorramps.pop()
starttext = starttext.replace("$message", getSaveString(text))
starttext = starttext.replace("$playername", getSaveString(username), 1)
complete = [starttext]
while len(colorramps):
startcolor = getColor(colorramps.pop())
colors = filter(None, re.split("#over\[([0-9a-fA-F]{6})\]", colorramps.pop()))
middletxt = colors.pop()
endcolor = getColor(colorramps.pop())
middletxt = middletxt.replace("$message", getSaveString(text))
middletxt = middletxt.replace("$playername", getSaveString(username), 1)
middletxt = middletxt.decode("utf")
if len(colors) > 0:
colors = map(getColor, colors)
colors.append(endcolor)
middletxt = rangeOverColors(middletxt, startcolor, colors)
else:
middletxt = getRangeString(middletxt, startcolor, endcolor)
middletxt = middletxt.encode("utf")
complete.append(middletxt)
endtext = colorramps.pop()
endtext …Run Code Online (Sandbox Code Playgroud) TypeError: Object of type 'filter' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
这真的让我很困惑。(我的 'realfiles' 函数只是确保目录列表不包含任何 Thumbs.db 或 .DS_Store 文件,即使我将其减少到“返回 True”,我也会得到同样的错误。)
我不是要序列化过滤器,无论这意味着什么。我正在序列化该过滤器的输出列表。对?Python 不是我最好的语言,所以我最初认为我的错误是试图将过滤器的输出分配给同一行中的会话变量 - 在 Javascript 中可以正常工作的东西 -
session['dir_listed_projects'] = filter( realfiles , pList )
session['dir_listed_templates'] = filter( realfiles , tList )
Run Code Online (Sandbox Code Playgroud)
所以我重写了它以分配给一个中间变量:
@app.route('/projects', methods=['GET', 'POST'])
def projects():
listA = listdir( outta( here, 2 ) + '/Projects')
listB = listdir( outta( here, 2 ) + '/_Templates')
pList = filter( realfiles , listA )
tList = filter( realfiles , listB )
session['dir_listed_projects'] = pList
session['dir_listed_templates'] …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Pyspark实现KMeans算法,它在while循环的最后一行给出了上述错误.它在循环外工作正常,但在我创建循环后它给了我这个错误我该怎么解决这个问题?
# Find K Means of Loudacre device status locations
#
# Input data: file(s) with device status data (delimited by '|')
# including latitude (13th field) and longitude (14th field) of device locations
# (lat,lon of 0,0 indicates unknown location)
# NOTE: Copy to pyspark using %paste
# for a point p and an array of points, return the index in the array of the point closest to p
def closestPoint(p, points):
bestIndex = 0
closest = float("+inf")
# …Run Code Online (Sandbox Code Playgroud) python ×11
filter ×3
python-3.x ×3
flask ×2
lambda ×2
list ×2
apache-spark ×1
k-means ×1
pyspark ×1
python-2.7 ×1
reduce ×1
regex ×1
variables ×1