相关疑难解决方法(0)

如何从python中的二维列表中获取所有可能的项目组合?

我没有找到更好的方法来在标题中表达这个问题.如果可以,请编辑.

我有一个这样的列表列表:

a = [['a','b'],[1,2]]
Run Code Online (Sandbox Code Playgroud)

现在,我想要一个能够吐出所有可能组合的函数:

[['a',1],['a',2],['b',1],['b',2]]
Run Code Online (Sandbox Code Playgroud)

预先知道a中的列表的数量,也不预先知道每个子列表的长度,但所有出现的组合应该包含每个子列表中的1个项目.

python list combinatorics

5
推荐指数
1
解决办法
1408
查看次数

set.union()抱怨它在传入生成器时没有参数

这是来自Wes Mckinney的Python for Data Analysis的第204页

genre_iter = (set(x.split('|')) for x in movies.genres)
genres = sorted(set.union(*genre_iter))
Run Code Online (Sandbox Code Playgroud)

%paste在IPython中使用该方法时,此代码非常有效.在Python shell中运行时,代码也可以正常运行.但是,当我直接在IPython中键入第二行时,没有%paste方法

genres = sorted(set.union(*genre_iter))
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

TypeError: descriptor 'union' of 'set' object needs an argument
Run Code Online (Sandbox Code Playgroud)

这似乎是一个bug,除非有一个我仍然没有意识到的IPython功能.

python generator ipython

4
推荐指数
1
解决办法
2242
查看次数

如何通过Python字符串切片反向旋转字符串

我需要反转一个交错的字符串,意味着我有2对,应该像这样搞砸了:

>>> interleaved = "123456"
Run Code Online (Sandbox Code Playgroud)

倒车

>>> print interleaved[::-1]
654321
Run Code Online (Sandbox Code Playgroud)

但我真正想要的是

563412
Run Code Online (Sandbox Code Playgroud)

这有一个字符串切片操作?

python string slice

4
推荐指数
1
解决办法
755
查看次数

有没有办法在python中删除列表?

我正在寻找一种潜入列表并直接访问其元素的方法.例如,以下是获取集合的笛卡尔乘积的常规方法.

>>> list(itertools.product((0,1), (0,1),(0,1),(0,1)))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]
Run Code Online (Sandbox Code Playgroud)

但是在这种情况下,这四个套装是相同的,很快就会一次又一次地输入它而变得无聊和烦人,这让人想到这样做:

>>> list(itertools.product([(0,1)]*4)
Run Code Online (Sandbox Code Playgroud)

但当然它不起作用,因为itertools.product函数会将其视为一组而不是四组.所以,问题是,有没有办法做到这一点:

>>> list(itertools.product(delist([(0,1)]*4))
Run Code Online (Sandbox Code Playgroud)

python data-structures

3
推荐指数
2
解决办法
4121
查看次数

将嵌套列表值附加到新列表中

我有一个程序,它有一个我希望访问的嵌套列表,然后根据条件附加到新列表.每个列表中有三,我希望知道如何单独访问它们.这是它目前的样子[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']].一个更好地解释这个问题的例子是,如果我想要第二列中的数据,那么我的新列表就会如此['B', 'E', 'H'].

这是我到目前为止,但我现在相当困难..

n = 0
old_list = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
new_list = []

for a, sublist in enumerate(old_list):
       for b, column in enumerate(sublist):
              print (a, b, old_list[a][b])
              if n == 0:
                     new_list.append(column[0])
              if n == 1:
                     new_list.append(column[1])
              if n == 2:
                     new_list.append(column[2])

print(new_list)         
Run Code Online (Sandbox Code Playgroud)

我目前的输出..

0 0 A
0 1 B
0 2 C
1 0 D
1 1 …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

3
推荐指数
1
解决办法
116
查看次数

以下代码中的 zip(*res) 在 python 中是什么意思?

这是 github 上 Allen Downey 的 Think Bayes 书中的一段代码:

def ReadData(filename='showcases.2011.csv'):
    """Reads a CSV file of data.
    Args:
      filename: string filename
    Returns: sequence of (price1 price2 bid1 bid2 diff1 diff2) tuples
    """
    fp = open(filename)
    reader = csv.reader(fp)
    res = []

    for t in reader:
        _heading = t[0]
        data = t[1:]
        try:
            data = [int(x) for x in data]
            # print heading, data[0], len(data)
            res.append(data)
        except ValueError:
            pass

    fp.close()
    return zip(*res)
Run Code Online (Sandbox Code Playgroud)

整个文件可以在这个 URL看到:Github 上这个文件的链接。

我想弄清楚 zip(*res) 在最后一行代码中是什么意思?具体来说: …

python zip function

3
推荐指数
1
解决办法
3467
查看次数

Python方法采用一个位置参数,但给出了两个

我遇到了一个我不太明白的错误.如果我有以下代码段:

class Test(object):
  def __init__(self):
    self.data = {}

  def update_data(self, **update):
    self.data = update

t = Test()

t.update_data(test='data') #  Works
t.update_data({'test':'data'}) #  TypeError: update_data() takes 1 positional argument but 2 were given
Run Code Online (Sandbox Code Playgroud)

所以根据我的理解,**update语法是字典破坏语法,当你将dict传递给函数时,它会被转换为关键字参数.

我在这里不正确地理解了什么?

python dictionary function keyword-argument

3
推荐指数
1
解决办法
1717
查看次数

在 Python 中 *zip(list1, list2) 返回什么类型的对象?

可能的重复:
Python:一劳永逸。Python 中的 Star 运算符是什么意思?

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
list(zipped)

x2, y2 = zip(*zip(x, y))
x == list(x2) and y == list(y2)
Run Code Online (Sandbox Code Playgroud)

*zip(x, y)返回什么类型的对象?为什么

res = *zip(x, y)
print(res)
Run Code Online (Sandbox Code Playgroud)

不起作用?

python zip list python-3.2

2
推荐指数
1
解决办法
3245
查看次数

Python zip单个列表元素

我有这个:

t=[(1,2,3),(4,5,6),(11,22,33),(44,55,66)]
Run Code Online (Sandbox Code Playgroud)

并想要得到这个:

[(1,4,11,44),(2,5,22,55),(3,6,33,66)]
Run Code Online (Sandbox Code Playgroud)

如何以pythonic方式进行操作。

python

2
推荐指数
1
解决办法
2979
查看次数

星号`*`如何在Python 3中的字符串格式化方法`.format(*)`中工作?

什么是使用*.format(*)?在下面的格式函数中使用它时,print(new_string.format(*sum_string))它会将输出中sum_string的值从18更改为1为什么会发生这种情况?我已阅读以下链接*args,**kwargs但无法理解这是如何适用于该.format()功能

**(双星/星号)和*(星号/星号)对参数有什么作用?

sum_string = "18"
new_string = "This is a new string of value {}"

print(new_string.format(sum_string)) #it provides an output of value 18
print(new_string.format(*sum_string)) #it provides an output of value 1
Run Code Online (Sandbox Code Playgroud)

python string.format string-formatting args python-3.x

2
推荐指数
1
解决办法
1029
查看次数