我有一个MxN的二维整数数组,我想将数组扩展为(BM)x(BN),其中B是方形图块边的长度,因此输入数组的每个元素作为BxB块重复在最后的数组中.下面是嵌套for循环的示例.有更快/内置的方式吗?
import numpy as np
a = np.arange(9).reshape([3,3]) # input array - 3x3
B=2. # block size - 2
A = np.zeros([a.shape[0]*B,a.shape[1]*B]) # output array - 6x6
# Loop, filling A with tiled values of a at each index
for i,l in enumerate(a): # lines in a
for j,aij in enumerate(l): # a[i,j]
A[B*i:B*(i+1),B*j:B*(j+1)] = aij
Run Code Online (Sandbox Code Playgroud)
结果......
a= [[0 1 2]
[3 4 5]
[6 7 8]]
A = [[ 0. 0. …Run Code Online (Sandbox Code Playgroud) 我正在编写样板,处理命令行参数,稍后将传递给另一个函数.这个其他函数将处理所有目录创建(如果需要).因此我的bp只需要检查输入字符串是否是有效目录,或者是有效文件,还是其他东西.即它需要区分"c:/ users/username /"和"c:/users/username/img.jpg"之类的东西
def check_names(infile):
#this will not work, because infile might not exist yet
import os
if os.path.isdir(infile):
<do stuff>
elif os.path.isfile(infile):
<do stuff>
...
Run Code Online (Sandbox Code Playgroud)
标准库似乎没有提供任何解决方案,但理想的是:
def check_names(infile):
if os.path.has_valid_dir_syntax(infile):
<do stuff>
elif os.path.has_valid_file_syntax(infile):
<do stuff>
...
Run Code Online (Sandbox Code Playgroud)
在打字时考虑问题之后,我无法理解一种检查(仅基于语法)字符串是否包含除文件扩展名和尾部斜杠之外的文件或目录(两者都可能不存在)的方法.可能刚刚回答了我自己的问题,但是如果有人想到我的随意,请发帖.谢谢!
我有一个csv文件,其头部位于数据列的顶部,如...
a,b,c
1,2,3
4,5,6
7,8,9
Run Code Online (Sandbox Code Playgroud)
(即标准表格数据)
在阅读本文时,DictReader我使用嵌套循环将行中的项目附加到相应键中的列表中
desired_result = {'a': [1, 4, 7], 'b': [2, 5, 8], 'c': [3, 6, 9]}
Run Code Online (Sandbox Code Playgroud)
第一个循环将dict中的所有值设置为空列表.下一个循环遍历从csv文件读入的每一行,DictReader从中创建键值的dict.内部循环将值附加到与相应键值匹配的列表中,因此我最终得到所需的词典列表.我最终不得不经常写这个.
我的问题是,有更多的Pythonic方法使用没有嵌套循环的内置函数,或更好的习惯用法,或存储此数据结构的替代方法,以便我可以通过查询键值返回可索引列表?如果是这样,还有一种方法可以格式化由前面的列提取的数据吗?(对于MWE,只需将上面的数据复制到文本文件中并通过代码运行)提前感谢!