简体   繁体   English

Fortran中以下Python列表理解的等效项是什么?

[英]What is the equivalent of the following Python list comprehension in Fortran?

I am trying to write the following list comprehension(written in Python) in Fortran. 我正在尝试在Fortran中编写以下列表理解(用Python编写)。

lit = [[x,y] for x in [p,q,r] for y in [h,k,l] if [x,y]!=[a,b]]

where a, b, p ,q ,r, h, k, l are integers 其中a, b, p ,q ,r, h, k, l是整数

How can I achieve it if I want to fill columns first in 2D Fortran array? 如果要先在2D Fortran数组中填充列,如何实现?

The Python code returns a list. Python代码返回一个列表。 It is equivalent to 相当于

for x in [p,q,r]:
     for y in [h,k,l]:
         if [x,y]!=[a,b]:
             list.append([x,y])

I made two sublists in Fortran. 我在Fortran中创建了两个子列表。 sublist_x and sublist_y where each list contains p,q,r and h,k,l respectively. sublist_xsublist_y ,其中每个列表分别包含p,q,rh,k,l

integer :: list(0:7), sublist_x(0:2),sublist_y(0:2), count
 count =-1

do i=0,7
   if (i%3 ==0)
   count = count +1
   endif
   list(0,i)=sublist_x(i%3)
   list(1,i)=sublist_y(count%3)
enddo

I think this is a complex way of doing things... 我认为这是一种复杂的处理方式...

If I understand correctly you want the cartesian product of the two little lists, excluding the element [a,b] ? 如果我理解正确,则需要两个小列表的笛卡尔积,但不包括元素[a,b] If I misunderstand, stop reading now. 如果我误会了,请立即停止阅读。 Here's a little program that almost does what you want ... 这是一个几乎可以满足您需要的小程序...

PROGRAM test

  IMPLICIT NONE

  INTEGER, DIMENSION(:), ALLOCATABLE :: listx, listy, bad_element
  INTEGER, DIMENSION(:,:), ALLOCATABLE :: outlist
  INTEGER :: ix, jx, alstat, n_elements

  LOGICAL, DIMENSION(:), ALLOCATABLE :: rows

  listx = [1,2,3]
  listy = [21,22,23]
  bad_element = [3,21]

  n_elements = SIZE(listx)*SIZE(listy)
  ALLOCATE(outlist(2,n_elements),stat=alstat)
  IF (alstat/=0) THEN
     WRITE(*,*) "something went wrong allocating the result array"
     STOP
  ELSE
     outlist(1,:) = RESHAPE(listx,[n_elements],listx)
     outlist(2,:) = RESHAPE(SPREAD(listy,1,SIZE(listx)),[n_elements])
  END IF

  DO ix = 1, n_elements
     IF (ALL(outlist(:,ix)==bad_element)) THEN
        outlist(:,ix:) = EOSHIFT(outlist(:,ix:),1,dim=2)
     END IF
  END DO

END PROGRAM TEST

At the end of this program outlist contains the cartesian product with any elements equal to the bad element replaced by 0 s and pushed to the end of outlets . 在该程序的末尾, outlist包含笛卡尔积,其等于坏元素的任何元素都替换为0 s,并推送到outlets的末尾。 For the hard-wired numbers above, the output is: 对于上面的固定数字,输出为:

    1    2    1    2    3    1    2    3    0
   21   21   22   22   22   23   23   23    0

I guess you shouldn't have too much difficulty trimming this to remove the 0 s, nor in packaging this program into a routine. 我想您应该不费吹灰之力地将其删除以消除0 s,也不必将此程序打包到例程中。 And I hope the code explains itself. 我希望代码能够自我解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM