[英]What is the equivalent of the following Python list comprehension in Fortran?
我正在嘗試在Fortran中編寫以下列表理解(用Python編寫)。
lit = [[x,y] for x in [p,q,r] for y in [h,k,l] if [x,y]!=[a,b]]
其中a, b, p ,q ,r, h, k, l
是整數
如果要先在2D Fortran數組中填充列,如何實現?
Python代碼返回一個列表。 相當於
for x in [p,q,r]:
for y in [h,k,l]:
if [x,y]!=[a,b]:
list.append([x,y])
我在Fortran中創建了兩個子列表。 sublist_x
和sublist_y
,其中每個列表分別包含p,q,r
和h,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
我認為這是一種復雜的處理方式...
如果我理解正確,則需要兩個小列表的笛卡爾積,但不包括元素[a,b]
? 如果我誤會了,請立即停止閱讀。 這是一個幾乎可以滿足您需要的小程序...
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
在該程序的末尾, outlist
包含笛卡爾積,其等於壞元素的任何元素都替換為0
s,並推送到outlets
的末尾。 對於上面的固定數字,輸出為:
1 2 1 2 3 1 2 3 0
21 21 22 22 22 23 23 23 0
我想您應該不費吹灰之力地將其刪除以消除0
s,也不必將此程序打包到例程中。 我希望代碼能夠自我解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.