你知道最好的方法吗:
let toTableau2D (seqinit:seq<'a*'b*'c>) =
let myfst = fun (a,b,c) -> a
let myscd = fun (a,b,c) -> b
let mytrd = fun (a,b,c) -> c
let inputd = seqinit |> groupBy2 myfst myscd
Run Code Online (Sandbox Code Playgroud)
必须有一个比重写fst更好的方法..
更新 在pad建议之后,我重写了将之前的'a*'b打包成单个结构我的代码现在看起来像
let toTableau (seqinit:seq<'a*'b>) =
let inputd = seqinit |> Seq.groupBy fst |> toMap
let keys = seqinit |> Seq.map fst |> Set.ofSeq |> List.ofSeq
...
Run Code Online (Sandbox Code Playgroud) 我喜欢在作业的右侧使用元组拆包:
>>> a = [3,4]
>>> b = [1,2,*a]
File "<stdin>", line 1
SyntaxError: can use starred expression only as assignment target
Run Code Online (Sandbox Code Playgroud)
当然,我可以这样做:
>>> b = [1,2]
>>> b.extend(a)
>>> b
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
但我认为这很麻烦.我有点意思吗?一个简单的方法?它有计划吗?或者是否有理由明确没有使用该语言?
部分问题是所有容器类型都使用构造函数,该构造函数期望迭代,并且不接受*args参数.我可以继承,但是这会给其他人应该阅读的脚本引入一些非pythonic噪声.
我需要知道为什么这会失败:
class ConfigurationError(Exception):
def __init__(self, *args):
super(ConfigurationError, self).__init__(self, args)
self.args = list(args)
# Do some formatting on the message string stored in self.args[0]
self.args[0]=self.__prettyfi(self.args[0])
def __prettyfi(self, arg):
pass
# Actual function splits message at word
# boundaries at pos rfind(arg[1:78]) if len(arg) >78
# it does this by converting a whitespace char to a \n
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,我收到以下消息:
<snip>
ConfigurationError.py", line 7, in __init__
self.args[0]=self.__prettyfi(self.args[0])
TypeError: 'tuple' object does not support item assignment
我编辑了第一行.匹配此代码示例.
我不明白为什么self.args = list(args)没有正确地将元组解压缩到第5行的列表中.
(我有一种潜行的怀疑,我没记得超基本的东西...)
我想附加一个包含函数返回值列表的表,其中一些是元组:
def get_foo_bar():
# do stuff
return 'foo', 'bar'
def get_apple():
# do stuff
return 'apple'
table = list()
table.append([get_foo_bar(), get_apple()])
Run Code Online (Sandbox Code Playgroud)
这会产生:
>>> table
[[('foo', 'bar'), 'apple']]
Run Code Online (Sandbox Code Playgroud)
但我需要将返回的元组解压缩到该列表中,如下所示:
[['foo', 'bar', 'apple']]
Run Code Online (Sandbox Code Playgroud)
由于解包函数调用[*get_foo_bar()]不起作用,我分配了两个变量用于接收元组的值并改为添加它们:
foo, bar = get_foo_bar()
table.append([foo, bar, get_apple()])
Run Code Online (Sandbox Code Playgroud)
这有效,但可以避免吗?
我有一些输入值的列表,其中第一对是强制性的,最后一对是可选的.是否有任何简单的方法可以使用元组解包将这些分配给变量,如果缺少可选参数则获取None.
例如.
a = [1,2]
foo, bar, baz = a
# baz == None
Run Code Online (Sandbox Code Playgroud)
理想情况下,可以是任何长度 - 包括超过3(其他物品扔掉).
目前我正在使用带有参数名称列表的zip来获取字典:
items = dict(zip(('foo', 'bar', 'baz'), a))
foo = items.get('foo', None)
bar = items.get('bar', None)
baz = items.get('baz', None)
Run Code Online (Sandbox Code Playgroud)
但它有点啰嗦.
我有一个元组列表,每个元组包含1到5个元素.我想将这些元组解压缩为五个值,但这对于少于五个元素的元组不起作用:
>>> t = (1,2) # or (1) or (1,2,3) or ...
>>> a,b,c,d,e = (t)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack
Run Code Online (Sandbox Code Playgroud)
可以将不存在的值设置为None.基本上,如果这个函数我正在寻找更好(更密集)的方法:
def unpack(t):
if len(t) == 1:
return t[0], None, None, None, None
if len(t) == 2:
return t[0], t[1], None, None, None
if len(t) == 3:
return t[0], t[1], t[2], None, None
if len(t) == 4:
return t[0], t[1], t[2], t[3], None …Run Code Online (Sandbox Code Playgroud) 有没有办法使用'splat'运算符(例如a, *rest = somelist)以消耗一定数量的项目?
使用案例:我想将一些输入分成一个数字,一个列表列表,另一个数字和另一个列表列表.
我的输入如下:
5
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
5
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Run Code Online (Sandbox Code Playgroud)
而我想的名字first_num,first_arrangement,second_num,second_arrangement使得:
first_num == 5
first_arrangement == [[1, 2, 3, 4], [5, 6, 7, 8], ...]
Run Code Online (Sandbox Code Playgroud)
等等.
要做到这一点,能够从我已经产生线的迭代中消耗一定数量的项是有用的.像这样的东西作为中间步骤是理想的:
first_num, *[4]first_arrangement, second_num, *[4]second_arrangement = lines
解决这个问题的正常/规范/ Pythonic方法是什么?
我有一个列表列表,我需要迭代3次(3个嵌套循环)
rangeList = [[-0.18,0.18],[0.14,0.52],[0.48,0.85]]
Run Code Online (Sandbox Code Playgroud)
我可以使用如下产品的产品实现这一点
from itertools import product
for val in product(product(rangeList,rangeList),rangeList):
print val
Run Code Online (Sandbox Code Playgroud)
输出如下
(([-0.18, 0.18], [-0.18, 0.18]), [-0.18, 0.18])
(([-0.18, 0.18], [-0.18, 0.18]), [0.14, 0.52])
(([-0.18, 0.18], [-0.18, 0.18]), [0.48, 0.85])
(([-0.18, 0.18], [0.14, 0.52]), [-0.18, 0.18])
Run Code Online (Sandbox Code Playgroud)
它是一个元组元组.我的问题是
val成3个独立的变量说xRange,yRange并且
zRange,每个拥有发言权的列表值[-0.18, 0.18]或[0.14, 0.52]等.我有一个由混合字典和列表组成的数据结构.我试图解压缩这个以获得键的元组和每个键的所有子值.
我正在使用列表推导,但只是没有让它工作.我哪里错了?
我看到了有关拆包列表中,列出了许多其他的答案(如1,2),但找不到一个例子,其中对多个子值的单个键解包.
码:
dict_of_lists = {'A':[{'x':1},{'x':2}], 'B':[{'x':3},{'x':4}] }
print [(key,subdict[subkey],) for key in dict_of_lists.keys() for subdict in dict_of_lists[key] for subkey in subdict.keys()]
Run Code Online (Sandbox Code Playgroud) 我经常对Python的可迭代解包缺乏灵活性感到沮丧.
请看以下示例:
a, b = range(2)
Run Code Online (Sandbox Code Playgroud)
工作良好.正如预期的那样a包含0和b包含1.现在让我们试试这个:
a, b = range(1)
Run Code Online (Sandbox Code Playgroud)
现在,我们得到一个ValueError:
ValueError: not enough values to unpack (expected 2, got 1)
Run Code Online (Sandbox Code Playgroud)
不理想,当期望的结果是0在a和None中b.
有很多黑客可以解决这个问题.我见过的最优雅的是:
a, *b = function_with_variable_number_of_return_values()
b = b[0] if b else None
Run Code Online (Sandbox Code Playgroud)
不漂亮,可能会让Python新手感到困惑.
那么最恐怖的方式是什么?将返回值存储在变量中并使用if块?该*varname黑客?别的什么?
python ×9
tuples ×4
python-3.x ×3
python-2.7 ×2
cons ×1
dictionary ×1
f# ×1
flatten ×1
list ×1
python-3.2 ×1