小编nor*_*ius的帖子

询问用户输入,直到他们给出有效的响应

我正在编写一个必须接受用户输入的程序.

#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18: 
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")
Run Code Online (Sandbox Code Playgroud)

如果用户输入合理数据,这将按预期工作.

C:\Python\Projects> canyouvote.py
Please enter your age: 23
You are able to vote in the United States!
Run Code Online (Sandbox Code Playgroud)

但如果他们犯了错误,那就崩溃了:

C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Traceback (most recent call last):
  File "canyouvote.py", line 1, in …
Run Code Online (Sandbox Code Playgroud)

python validation loops user-input python-3.x

523
推荐指数
10
解决办法
42万
查看次数

Pandas join问题:列重叠但未指定后缀

我有以下2个数据框:

df_a =

     mukey  DI  PI
0   100000  35  14
1  1000005  44  14
2  1000006  44  14
3  1000007  43  13
4  1000008  43  13

df_b = 
    mukey  niccdcd
0  190236        4
1  190237        6
2  190238        7
3  190239        4
4  190240        7
Run Code Online (Sandbox Code Playgroud)

当我尝试加入这两个数据帧时:

join_df = df_a.join(df_b,on='mukey',how='left')
Run Code Online (Sandbox Code Playgroud)

我收到错误:

*** ValueError: columns overlap but no suffix specified: Index([u'mukey'], dtype='object')
Run Code Online (Sandbox Code Playgroud)

为什么会这样?数据帧确实具有常见的"mukey"值.

python join pandas

119
推荐指数
4
解决办法
13万
查看次数

将列按名称移动到pandas中的表格前面

这是我的df:

                             Net   Upper   Lower  Mid  Zsore
Answer option                                                
More than once a day          0%   0.22%  -0.12%   2    65 
Once a day                    0%   0.32%  -0.19%   3    45
Several times a week          2%   2.45%   1.10%   4    78
Once a week                   1%   1.63%  -0.40%   6    65
Run Code Online (Sandbox Code Playgroud)

如何按名称("Mid")将列移动到表的前面,索引0.这是它需要的样子:

                             Mid   Upper   Lower  Net  Zsore
Answer option                                                
More than once a day          2   0.22%  -0.12%   0%    65 
Once a day                    3   0.32%  -0.19%   0%    45
Several times a week          4   2.45%   1.10%   2%    78
Once a …
Run Code Online (Sandbox Code Playgroud)

python move shift dataframe pandas

61
推荐指数
7
解决办法
6万
查看次数

Python argparse:很多选择导致丑陋的帮助输出

我有这个代码,我通常很高兴:

import argparse

servers = [ "ApaServer", "BananServer", "GulServer", "SolServer", "RymdServer",
            "SkeppServer", "HavsServer", "PiratServer", "SvartServer", "NattServer", "SovServer" ]

parser = argparse.ArgumentParser(description="A program to update components on servers.")
group = parser.add_mutually_exclusive_group()
group.add_argument('-l', '--list', dest="update", action='store_false', default=False, help='list server components')
group.add_argument('-u', '--updatepom', dest="update", action='store_true', help='update server components')
parser.add_argument('-o', '--only', nargs='*', choices=servers, help='Space separated list of case sensitive server names to process')
parser.add_argument('-s', '--skip', nargs='*', choices=servers, help='Space separated list of case sensitive server names to exclude from processing')
args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)

我喜欢选择=服务器为我验证输入中的服务器名称,所以我不必这样做.但是,有这么多有效的选择会使帮助输出看起来很糟糕:

usage: …
Run Code Online (Sandbox Code Playgroud)

python argparse

48
推荐指数
5
解决办法
3万
查看次数

线性索引上三角矩阵

如果我有一个矩阵的上三角形部分,在对角线上方偏移,存储为线性数组,那么如何(i,j)从数组的线性索引中提取矩阵元素的索引?

例如,线性阵列[a0, a1, a2, a3, a4, a5, a6, a7, a8, a9是矩阵的存储

0  a0  a1  a2  a3
0   0  a4  a5  a6
0   0   0  a7  a8
0   0   0   0  a9
0   0   0   0   0
Run Code Online (Sandbox Code Playgroud)

并且我们想要知道数组中的(i,j)索引,该索引对应于线性矩阵中的偏移,而没有递归.

例如,合适的结果k2ij(int k, int n) -> (int, int)将满足

k2ij(k=0, n=5) = (0, 1)
k2ij(k=1, n=5) = (0, 2)
k2ij(k=2, n=5) = (0, 3)
k2ij(k=3, n=5) = (0, 4)
k2ij(k=4, n=5) = (1, 2)
k2ij(k=5, n=5) = (1, 3) …
Run Code Online (Sandbox Code Playgroud)

c++ arrays numpy linear-algebra triangular

32
推荐指数
3
解决办法
9083
查看次数

Python unittest:如何断言文件或文件夹的存在并在失败时打印路径?

在 python 中test case,我想断言文件或文件夹的存在,并在断言失败时提供有用的错误消息。我怎么能这样做呢?

以下当然有效,但它不会在错误消息中产生路径/文件名:

import unittest
import pathlib as pl

class TestCase(unittest.TestCase):
    def test(self):
        # ...
        path = pl.Path("a/b/c.txt")
        self.assertTrue(path.is_file())
        self.assertTrue(path.parent.is_dir())

if __name__ == "__main__":
    unittest.main(verbosity=2)
Run Code Online (Sandbox Code Playgroud)
import unittest
import pathlib as pl

class TestCase(unittest.TestCase):
    def test(self):
        # ...
        path = pl.Path("a/b/c.txt")
        self.assertTrue(path.is_file())
        self.assertTrue(path.parent.is_dir())

if __name__ == "__main__":
    unittest.main(verbosity=2)
Run Code Online (Sandbox Code Playgroud)

在较大的测试中,一目了然地看到哪个文件断言失败可能是有益的。如何扩展unittest.TestCase以针对此类测试打印更好的断言消息?

======================================================================
FAIL: test (__main__.TestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "my_test.py", line 194, in test
    self.assertTrue(path.is_file())
AssertionError: False is not true
Run Code Online (Sandbox Code Playgroud)

python python-unittest

14
推荐指数
2
解决办法
2万
查看次数

如何通过二进制可执行文件扩展Python包?

我的包几乎完全是用 python 编写的。但是,某些功能基于在 python 中使用subprocess. 如果我在本地设置包,我需要首先编译相应的 C++ 项目(由 CMake 管理)并确保在 bin 文件夹中创建生成的二进制可执行文件。然后我的 python 脚本就可以调用这些实用程序。

我的项目的文件夹结构类似于以下内容:

root_dir
- bin 
   - binary_tool1
   - binary_tool2
- cpp
   - CMakeLists.txt
   - tool1.cpp
   - tool2.cpp
- pkg_name
   - __init__.py
   - module1.py
   - module2.py
   - ...
LICENSE
README
setup.py
Run Code Online (Sandbox Code Playgroud)

我现在考虑创建一个可分发的 python 包并通过PyPi/pip发布它。因此,我需要将 C++ 项目的构建步骤包含到打包过程中。

到目前为止,我创建了 python 包(没有二进制“有效负载”),如本教程中所述。我现在想知道如何扩展打包过程,以便 C++ 二进制文件与包一起分发。

问题:

  • setuptools专为这样的用例而设计的吗?
  • 这种“混合”包方法是否可行,或者是否会出现二进制兼容性问题?

我相信用 C 代码扩展纯 python 包的规范方法是创建“二进制扩展”(例如使用distutils,或如此处所述。在这种情况下,功能由可执行文件提供,而不是由可包装的 C/C++ 函数提供。我想避免重新设计 C++ 项目来创建二进制扩展。

python distutils setuptools pypi

11
推荐指数
1
解决办法
1321
查看次数

Python与scikit-image反转颜色背面和白色

我用ndimage读取图像,图像结果如下: 在此输入图像描述

我想要反映这个图像

黑色 - >白色和白色 - >黑色

因此,使用分水岭进行迭代可以打破这个黑色物体.

请帮我.谢谢

python image image-processing scipy scikit-image

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

为什么python字典对于python3.7是不可逆的?

从3.7开始,保证标准的python词典保持插入顺序。(*)

d = {'b': 1, 'a': 2}
for k in d: 
    print(k)
# Prints always 'b' before 'a'.
Run Code Online (Sandbox Code Playgroud)

换句话说,字典键会严格保持顺序。原则上,这将允许密钥是可逆的。但是,以下任何一项均无效:

# TypeError: 'dict' object is not reversible
for k in reversed(d): 
    print(k)

# TypeError: 'dict_keys' object is not reversible
for k in reversed(d.keys()): 
    print(k)
Run Code Online (Sandbox Code Playgroud)

问题:此行为背后的原因是什么?为什么没有使命令具有可逆性?将来有什么计划改变这种行为?

解决方法当然可以:

for k in reversed(list(d.keys())): 
    print(k)
Run Code Online (Sandbox Code Playgroud)

(*)作为事实上,这种情况已经为Python 3.6的典型安装,如在讨论这个职位


更新:从python 3.8字典开始实际上是可逆的。可接受的答案是指Guido与其他导致该决定的核心开发人员之间的讨论。简而言之,他们权衡了语言一致性,实现工作和用户的实际利益。

dictionary python-3.x

9
推荐指数
1
解决办法
131
查看次数

QML:有条件地设置属性组的不同属性

如何有条件地一次性设置属性组的不同属性?

示例:假设有一个_context.condition可用的上下文属性.鉴于该值,我想为qml项设置不同的锚点.

// Some item...
Rectangle {
    id: square
    width: 50
    height: 50

    // For simple properties this should work:
    color: { if (_context.condition) "blue"; else "red" }

    // But how to do it for complex properties like 'anchors'?
    // Note that I set different properties for different values of the condition.
    // Here is how I would do it, but this does not work:
    anchors: { 
        if (_context.condition) {
            // Anchors set 1:
            horizontalCenter: parent.horizontalCenter
            bottom: parent.bottom …
Run Code Online (Sandbox Code Playgroud)

qt qml

7
推荐指数
1
解决办法
4246
查看次数