我不确定为什么下面的代码有效。根据文档,map 仅采用一个函数作为第一个参数,并将其应用于一个或多个可迭代对象,具体取决于函数采用的参数数量。
map(function, iterable..)
但是,您可以传递多个函数来代替可迭代对象,并且以某种方式将它们视为可迭代对象。不知何故,这一行将函数 add、square 和 str 视为可迭代对象。
函数如何被视为有效的可迭代对象?
def add(x):
return x + x
def square(x):
return x * x
nums = [1, 2, 3, 4, 5]
for i in nums:
vals = list(map(lambda x: x(i), (add, square, str)))
print(vals)
Run Code Online (Sandbox Code Playgroud)
返回:
[2, 1, '1']
[4, 4, '2']
[6, 9, '3']
[8, 16, '4']
[10, 25, '5']
Run Code Online (Sandbox Code Playgroud)
*编辑马丁回答了问题。此代码执行相同的操作,但将其从 lambda 函数中分离出来,显示add, square, str函数是如何迭代的。
[2, 1, '1']
[4, 4, '2']
[6, 9, '3']
[8, 16, '4']
[10, 25, '5'] …Run Code Online (Sandbox Code Playgroud) 我试图默认检查第一个单选按钮,以下代码可以帮助我做到这一点。加载页面时,会检查第一个单选按钮,但我面临的问题是它不允许我检查数组中也存在的其他按钮。
constructor(props: any) {
super(props);
this.state = {
selectedSort: '',
sort: ['Apple', 'Orange '],
}
}
this.state.sort.map((sortType:string, index:number) => {
return <span key={`${sortType}${index}` onClick={() => this.setSort(sortType)} >
<input type="radio" id={sortType}
value={this.state.selectedSort}
name={sortType} defaultChecked={index===0}
}/>
<span>{sortType}</span>
})
private setSort = (selectedSort: string) => {
this.setState({
selectedSort: selectedSort
});
}
Run Code Online (Sandbox Code Playgroud) 说我有一个方法:
def add_force_coupling(g1, g2, name):
print {(g1,g2): name}
Run Code Online (Sandbox Code Playgroud)
那么代码:
l = 3
for g1 in range(l):
for g2 in range(l):
name = 'G' + str(g1) + str(g2)
add_force_coupling(g1, g2, name)
Run Code Online (Sandbox Code Playgroud)
产生结果:
{(0, 0): 'G00'}, {(0, 1): 'G01'}, {(0, 2): 'G02'}, {(1, 0): 'G10'}, ..., {(2, 2): 'G22'}
Run Code Online (Sandbox Code Playgroud)
现在我想通过使用该map()函数使这更加pythonic .到目前为止我有:
list1 = sorted(l*range(l))
list2 = l*range(l)
list3 = ["".join(values) for values in zip(l*l*'G',list(map(str,l1)),list(map(str,l2)))]
map( add_force_coupling, list1, list2, list3 )
Run Code Online (Sandbox Code Playgroud)
这不正是我想要什么,但比标准的双回路丑陋,因为INT表需要转换到str在list3.此外,很难理解发生了什么.是否有一个重写的双循环的任何更好的Python的方式map(),zip()或以其他方式?
注意:不能选择更改方法
鉴于以下测试:
>>> import timeit
>>> timeit.timeit("[x + 'abc' for x in ['x', 'y', 'z']]")
>>> timeit.timeit("map(lambda x: x + 'abc', ['x', 'y', 'z'])")
Run Code Online (Sandbox Code Playgroud)
使用Python 2.7和3.4(Debian 8/testing/jessie),我得到以下数字:
Python27 Python34
1.3s 0.5s map()
0.6s 0.9s list comprehension
Run Code Online (Sandbox Code Playgroud)
使用Python 3显着改善了地图,列表理解受到严重影响.
问题:将代码从Python 2移植到Python 3时,是否建议将列表推导更改为map()?
python performance list-comprehension python-3.x map-function
我需要在某些集合的所有行中找到一个特定的子文本,我最终得到了这个:
my @missing = grep { $_ ne '' } map { $1 if m/^prefix:\s+(.+):\s+suffix$/ } @lines;
Run Code Online (Sandbox Code Playgroud)
哪个工作正常.但是那个开头的grep(为了摆脱比赛没有发生的所有空情线)看起来很糟糕.
这样做有更干净的方法吗?
只是为了澄清,这里是示例输入和没有grep的输出:
my @lines = (
'drivel',
'prefix: matches: suffix',
'stuff',
'prefix: more: suffix'
);
my @selected = map { $1 if m/^prefix:\s+(.+):\s+suffix$/ } @lines;
print "found: $_\n" foreach @selected;
Run Code Online (Sandbox Code Playgroud)
需要输出:
found: matches
found: more
Run Code Online (Sandbox Code Playgroud)
输出得到以上:
found:
found: matches
found:
found: more
Run Code Online (Sandbox Code Playgroud) 我有两个代码片段,我认为这两个代码片段都会产生警报.但是,第一个结果为none,而第二个执行警报.
(map #(.alert js/window %) ["hey1" "hey2"])
Run Code Online (Sandbox Code Playgroud)
这个轻微的修改按预期打印(零nil),以及修复警报问题.问题是为什么?
(print (map #(.alert js/window %) ["hey1" "hey2"]))
Run Code Online (Sandbox Code Playgroud)
另一个奇怪的观察是,第一个代码片段来自浏览器 - repl,但不是在键入代码时.
地图功能副作用是免费的,但打印不是吗?也许我不知道一些核心代码优化?
解决方法和答案都很受欢迎.如果您需要更多信息,请在评论中告诉我.
[org.clojure/clojurescript"1.8.51"]
BOOT_CLOJURE_VERSION = 1.7.0
BOOT_VERSION = 2.5.5
java版"1.8.0_101"
说明:Ubuntu 14.04.4 LTS
我map用来处理Python3.6中的列表:
def calc(num):
if num > 5:
return None
return num * 2
r = map(lambda num: clac(num), range(1, 10))
print(list(r))
# => [2, 4, 6, 8, 10, None, None, None, None]
Run Code Online (Sandbox Code Playgroud)
我期望的结果是:[2, 4, 6, 8, 10]。
当然,我可以使用它filter来处理map结果。但是有没有办法map直接返回我想要的结果?
我试图使这个地图功能本身更具破坏性.这意味着map函数修改原始数组而不是新数组.
function map (array, callback) {
var result = []
for (var i = 0; i < array.length; i++) {
result.push(callback(array[i]))
}
console.log("Array",array, "Result",result)
return result
}
Run Code Online (Sandbox Code Playgroud)
console.log返回:
Array [ 5, 2, 1 ] Result [ 6, 3, 2 ]
Run Code Online (Sandbox Code Playgroud)
数组应为[5,2,1],目前为[6,3,2]
我想知道是否有可能filter仅使用mapPython中的函数来实现函数。假设我有一个列表,A = [1,2,3,4,5,6,7,8,9,10]而我只想得到偶数。应用filter函数为我提供了5个元素的列表,但是map无论我想到什么功能,总会返回10个元素。
有什么办法可以做到这一点?
请不要建议filter对的结果再次应用map。:-)
我有一个功能:
mapAtOriginal :: (a -> a) -> [Int] -> [a] -> [a]
mapAtOriginal f is xs = helper 0 is xs
where
helper _ [] xs = xs
helper c (i:is) (x:xs)
| c < i = x : helper (c+1) (i:is) xs
| otherwise = f x : helper (c+1) is xs
Run Code Online (Sandbox Code Playgroud)
它是这样的:
mapAtOriginal (*2) [0,3] [1,2,3,4] -- == [2,2,3,8]
Run Code Online (Sandbox Code Playgroud)
因此,我想使用map功能重写它。我知道这map适用于列表的每个元素,但是,我只需要将其应用于特定的索引。
我该怎么做?
map-function ×10
python ×5
python-3.x ×3
function ×2
arrays ×1
clojure ×1
filter ×1
for-loop ×1
haskell ×1
javascript ×1
methods ×1
performance ×1
perl ×1
printing ×1
radio-button ×1
reactjs ×1
recursion ×1