用numpy制作一个范围列表(Make a list of ranges in numpy)

我想列出一个随机起始点的整数序列列表。 我会在纯Python中执行此操作的方式是

x = np.zeros(1000, 10) # 1000 sequences of 10 elements each
starts = np.random.randint(1, 1000, 1000)
for i in range(len(x)):
    x[i] = np.arange(starts[i], starts[i] + 10)

我想知道是否有使用Numpy功能的更优雅的方式。


I want to make a list of integer sequences with random start points. The way I would do this in pure python is

x = np.zeros(1000, 10) # 1000 sequences of 10 elements each
starts = np.random.randint(1, 1000, 1000)
for i in range(len(x)):
    x[i] = np.arange(starts[i], starts[i] + 10)

I wonder if there is a more elegant way of doing this using Numpy functionality.


原文:https://stackoverflow.com/questions/39626041
2022-04-22 07:04

满意答案

编辑:

否则,如果你从给定的字符串开始,那么你应该像这样简单地切片:

a = a[1::2]
  1. 第一个元素1表示您想要从第二个元素开始切片元素。
  2. 最后一个元素2是间隔(每两个元素)
  3. 空的中间元素实际上是指数上限(独占)。 如果你不放任何东西意味着你想要所有物品。

原版的:

请参考您之前的问题:

如何使列表元素成为字符串?

从有a = [10, 20, 30]

为了从每个列表项目的第二个元素开始为给定的整数列表a获取连接字符串,可以使用[1::]从第二个元素开始将列表中的每个项目向前切片(索引1表示从第二个元素)是这样的:

a = [10, 20, 30]
a = [''.join(str(x)[1::] for x in a)]

print(a)

结果:

['000']

Edit:

Else, if you start from the given string, then you should simply slice it like this:

a = a[1::2]
  1. First element 1 means you want to slice the element starting from its second element.
  2. The last element 2 is the interval (every two element)
  3. The empty middle element is actually the upper index limit (exclusive). If you don't put anything means you want all items.

Original:

Refering from your previous question here:

How to make list elements into string?

Started from having a = [10, 20, 30],

In order to get the joined string for the given integer list a from the second element per list item onwards, you could slice each item of the list to from the second element onwards by using [1::] (index 1 means starting from the second element) like this:

a = [10, 20, 30]
a = [''.join(str(x)[1::] for x in a)]

print(a)

Result:

['000']

相关问答

更多

按特定月份切片(Slicing by specific month)

datetimeindex具有要访问的属性month ,您可以使用它来过滤df: In [132]: df = pd.DataFrame(index=pd.date_range(dt.datetime(2015,1,1), dt.datetime(2015,5,1))) df.loc[df.index.month==2] Out[132]: Empty DataFrame Columns: [] Index: [2015-02-01 00:00:00, 2015-02-02 00:00:00, ...

动态Python数组切片(Dynamic Python Array Slicing)

您可以使用python的slice 自动 slice : >>> a = np.random.rand(3, 4, 5) >>> a[0, :, 0] array([ 0.48054702, 0.88728858, 0.83225113, 0.12491976]) >>> a[(0, slice(None), 0)] array([ 0.48054702, 0.88728858, 0.83225113, 0.12491976]) slice方法读取为slice(*start*, st...

Python垂直阵列切片(Python Vertical Array Slicing)

my_list = [[1, A], [2, B], [3, C]] a, b = zip(*my_list) 请注意, a和b将最终成为元组。 my_list = [[1, A], [2, B], [3, C]] a, b = zip(*my_list) Note that a and b will end up being tuples.

Python切片不会更改切片数组的值(Python slicing does not change the sliced array's value)

+是一个函数,它返回一个新数组。 通过运行y + 100您运行了一个函数,该函数返回一个指向新数组的指针,该数组存储在y 。 如果你要运行y[0] = 5 , x也会改变。 在编辑中添加: +是numpy.add(y, 100)的隐式版本,广播100到[100, 100, 100, 100, 100, 100] numpy.add(y, 100) [100, 100, 100, 100, 100, 100] 。 然后它对两个数组求和,因此必须返回一个新数组。 numpy.add doc 另外,如评...

Python数组切片 - 如何实现二维数组切片?(Python array slicing — How can 2D array slicing be implemented?)

obj[,:3]是无效的Python,所以它会引发一个SyntaxError - 因此,你不能在你的源文件中使用该语法。 (当你尝试在numpy数组上使用它时也会失败) obj[,:3] is not valid python so it will raise a SyntaxError -- Therefore, you can't have that syntax in your source file. (It fails when you try to use it on a numpy ...

如何在Python中使用切片来选择其他的(How to select every other using slicing in Python)

编辑: 否则,如果你从给定的字符串开始,那么你应该像这样简单地切片: a = a[1::2] 第一个元素1表示您想要从第二个元素开始切片元素。 最后一个元素2是间隔(每两个元素) 空的中间元素实际上是指数上限(独占)。 如果你不放任何东西意味着你想要所有物品。 原版的: 请参考您之前的问题: 如何使列表元素成为字符串? 从有a = [10, 20, 30] , 为了从每个列表项目的第二个元素开始为给定的整数列表a获取连接字符串,可以使用[1::]从第二个元素开始将列表中的每个项目向前切片(索引1...

Python非线性切片(Python non-linear slicing)

编辑 :主要是我需要这个修改列表。 例如 a[*non-linear-slicing*] = [*list-with-new-values*] 大。 然后我们可以使用这个新值的列表来驱动这个事情。 演示: >>> a = range(17) >>> newvals = ['foo', 'bar', 'baz', 'qux'] >>> for i, val in enumerate(newvals): a[2**i] = val >>> a [0, 'foo', 'bar', ...

Python列表切片(Python list slicing)

一个简单的解决方案: array_ = [7,8,2,3,4,10,5,6,7,10,8,9,10,4,5,12,13,14,1,2,15,16,17] slice_ = [2, 4, 6, 8, 10, 12, 15, 17, 20, 22] intervals = [12, 17, 22] output = [] intermediate = [] for i in range(0, len(slice_), 2): intermediate.extend(array_[slice_...

反向切片Python(Slicing Python in Reverse)

切片从第一个数字(包括)转到第二个数字(不包括),步骤为第三个数字。 在您的情况下,第一个数字访问“4”,第二个数字访问“2”。 步长为-1时,它将从第一个数字(“4”)位置的字符开始,然后获得下一个字符(或步长为-1,实际上是前一个字符“3”),但会停在那里,因为第二个索引(2)是独占的。 要获得从“4”到“0”的所有内容,您可以执行x[4:0:-1]或者更方便的是x[:5] 。 Slicing goes from the first number (inclusive) to the seco...

在PHP中切片数组(Slicing arrays in PHP)

这些行返回我想要的关联数组: $filter=array_filter($select); $new=array_intersect_key($arr,$filter); var_dump($new); These lines return the associative array that I want: $filter=array_filter($select); $new=array_intersect_key($arr,$filter); var_dump($new);

相关文章

更多

A Great List of Windows Tools

Windowsis an extremely effective and a an efficient ...

Python 列表(list)操作

列表就像java里的collection,所具有的特性也要比元组更多,更灵活,其character总结 ...

Becoming a data scientist

Data Week: Becoming a data scientist Data Pointed, ...

源码解读Mybatis List列表In查询实现的注意事项

源码解读Mybatis List列表In查询实现的注意事项 在SQL开发过程中,动 ...

How to Start a Business in 10 Days

With an executive staffing venture about to open, a ...

hibernate 对list修改

class A{ private String a; private String b; pri ...

Drupal Forums instead of phpBB or vBulletin: A casestudy

5th Jan, 10 Drupal drupal advanced forum drupa ...

FreeMarker集合(List、Map)

我们上一节认识了FreeMarker基本数据类型,接口认识FreeMarker集合(List、Map) ...

Become a Master Designer: Rule Three: Contrast, Contrast, Contrast

Part Three of Seven Easy Principles to Becoming a M ...

[转]So You Want To Be A Producer

pro-du-cer n. 1. Someone from a game publisher who ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本