是这样的
def mymethod():
return [[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,2,3,4]]
mylist = mymethod()
for _, thing, _, _ in mylist:
print thing
# this bit is meant to be outside the for loop,
# I mean it to represent the last value thing was in the for
if thing:
print thing
Run Code Online (Sandbox Code Playgroud)
我想要做的是避免虚拟变量,是否有更聪明的方法来做到这一点
for thing in mylist:
print thing[1]
Run Code Online (Sandbox Code Playgroud)
因为那时我将不得不使用thing[1]任何其他时间我需要它,而不是将它分配给一个新的变量然后事情变得凌乱.
如果我错过了一些明显的东西,那么很抱歉
有更明智的方法吗?我想通过总结许多其他列表的索引来创建一个新列表.我对编程很新,这看起来像一个非常笨重的方法!
list1 = [1,2,3,4,5]
list2 = [1,1,1,4,1]
list3 = [1,22,3,1,5]
list4 = [1,2,5,4,5]
...
list100 = [4,5,6,7,8]
i = 0
while i < len(list1):
mynewlist[i] = list1[i]+list2[i]+list3[i]+list4[i]+...list100[i]
i = i+1
Run Code Online (Sandbox Code Playgroud) 我有一个词典列表(缩写).
my_list = [{ 'id':1, 'val':123 }, {'id':2, 'val':456 }, {'id':2, 'val':789 }]
Run Code Online (Sandbox Code Playgroud)
如何计算具有特定键的指定值的字典的出现次数(在本例中为' id')?有没有办法利用计数(my_list.count('id' = 1)?!?)
我正在使用Python,我注意到该map()功能似乎并没有做太多.例如,如果我写程序:
mylist = [1, 2, 3, 4, 5]
function = map(print, l)
print(function)
Run Code Online (Sandbox Code Playgroud)
它没有优势:
mylist = [1, 2, 3, 4, 5]
for item in mylist:
print(item)
Run Code Online (Sandbox Code Playgroud)
实际上,第二个选项创建的变量较少,对我来说整体看起来通常更清晰.我认为这map()提供了一个在例子中看不到的优点,但它究竟是什么?
编辑:似乎有些人一直在回答一个与我打算提出的问题不同的问题.制作Python的开发人员显然在创建map()函数方面做了一些工作,他们甚至决定不将它从3.0中删除,而是继续研究它.他们决定服务的基本功能是什么?
我一直在使用imran的很好的答案来展平嵌套的 Python 字典,压缩键,并试图想出一种方法来进一步展平可能位于字典项的列表值内的字典。(当然,因为我的数据通常来自 XML,这也可以是递归的......)
from pprint import pprint
from collections import MutableMapping
def flatten(d, parent_key='', sep='_'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, MutableMapping):
items.extend(flatten(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
Run Code Online (Sandbox Code Playgroud)
给定一个d这样的字典:
d = {"a": 1,
"b": 2,
"c": {"sub-a": "one",
"sub-b": "two",
"sub-c": "thre"}}
Run Code Online (Sandbox Code Playgroud)
这很好用:
pprint(flatten(d))
{'a': 1,
'b': 2,
'c_sub-a': 'one', …Run Code Online (Sandbox Code Playgroud) 我知道如何通过索引访问向量中的元素:
test = numpy.array([1,2,3,4,5,6])
indices = list([1,3,5])
print(test[indices])
Run Code Online (Sandbox Code Playgroud)
给出正确答案:[2 4 6]
但我正在尝试使用 2D 矩阵做同样的事情,例如:
currentGrid = numpy.array( [[0, 0.1],
[0.9, 0.9],
[0.1, 0.1]])
indices = list([(0,0),(1,1)])
print(currentGrid[indices])
Run Code Online (Sandbox Code Playgroud)
这应该为我显示“[0.0 0.9]”,表示矩阵中 (0,0) 处的值和 (1,1) 处的值。而是显示“[ 0.1 0.1]”。此外,如果我尝试使用 3 个索引:
indices = list([(0,0),(1,1),(0,2)])
Run Code Online (Sandbox Code Playgroud)
我现在收到以下错误:
Traceback (most recent call last):
File "main.py", line 43, in <module>
print(currentGrid[indices])
IndexError: too many indices for array
Run Code Online (Sandbox Code Playgroud)
我最终需要对这些索引处的所有元素应用一个简单的 max() 操作,并且需要以最快的方式来实现优化。
我究竟做错了什么 ?如何访问矩阵中的特定元素以非常有效的方式(不使用列表理解或循环)对它们进行一些操作。
Stack Overflow 上有很多关于这个一般主题的问答,但它们要么质量很差(通常是初学者的调试问题暗示的),要么以其他方式错过了目标(通常是不够通用)。至少有两种极其常见的方法会使幼稚的代码出错,初学者从关于循环的规范中获益更多,而不是从将问题作为拼写错误或关于打印所需内容的规范中获益。所以这是我尝试将所有相关信息放在同一个地方。
假设我有一些简单的代码,可以对一个值进行计算x并将其分配给y:
y = x + 1
# Or it could be in a function:
def calc_y(an_x):
return an_x + 1
Run Code Online (Sandbox Code Playgroud)
现在我想重复计算 的许多可能值x。我知道for如果我已经有要使用的值列表(或其他序列),我可以使用循环:
xs = [1, 3, 5]
for x in xs:
y = x + 1
Run Code Online (Sandbox Code Playgroud)
while或者,如果有其他逻辑来计算值序列,我可以使用循环x:
def next_collatz(value):
if value % 2 == 0:
return value // 2
else:
return 3 * value + 1
def collatz_from_19():
x = 19
while x != 1:
x …Run Code Online (Sandbox Code Playgroud) 我有一个清单
L = Counter(mywords)
Run Code Online (Sandbox Code Playgroud)
在哪里
mywords = ['Well', 'Jim', 'opportunity', 'I', 'Governor', 'University', 'Denver', 'hospitality', 'There', 'lot', 'points', 'I', 'make', 'tonight', 'important', '20', 'years', 'ago', 'I', 'luckiest', 'man', 'earth', 'Michelle', 'agreed', 'marry', '(Laughter)', 'And', 'I', 'Sweetie', 'happy']
Run Code Online (Sandbox Code Playgroud)
它比那要长得多,但这是一个片段。
现在我接下来要做的是:
print ("\n".join(c.most_common(10)))
Run Code Online (Sandbox Code Playgroud)
因为我希望它显示该列表中 10 个最常用的单词及其计数,但我希望它为列表中的每个项目打印出新行,而不是我收到此错误:
TypeError: sequence item 0: expected str instance, tuple found
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,使用 Python 3。
是否有更多Pythonic方法来定义此功能?
def idsToElements(ids):
elements = []
for i in ids:
elements.append(doc.GetElement(i))
return elements
Run Code Online (Sandbox Code Playgroud)
也许它可能与列表理解.我基本上希望获取一个id列表,并将它们更改为比定义函数更简单的元素列表.
在python中撰写地图功能
你好
今天,我使用两个映射调用将0 1字符串的掩码转换为布尔值:
>>> a, b = '10'
>>> a, b = map(int, (a, b))
>>> a, b = map(bool, (a, b))
>>> a, b
(True, False)
Run Code Online (Sandbox Code Playgroud)
只用一张地图怎么办?
python ×10
list ×3
dictionary ×2
arrays ×1
coding-style ×1
for-loop ×1
indices ×1
iteration ×1
matrix ×1
nested-lists ×1
python-2.7 ×1
python-3.x ×1
sum ×1
tuples ×1