0

[Visual Basic 陣列] 與 [Python列表]問題探討

``````#Python編寫：
a = []
for x in range(21):
if x%2==0:
a.append(x)
print(a)
``````
``````'Visual Basic編寫：
Sub main()
Dim so As New ArrayList
For x = 0 To 20
If x Mod 2 = 0 Then
so.Add(x)
End If
Next
End Sub
``````

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

``````#Python List comprehension寫法：
a = [x for x in range(21) if x%2==0]
print(a)
``````
``````'Visual Basic
??????
``````
1. 使用VB做得到類似Python的List comprehension寫法嗎?
1. VB除了普通寫法，還有其他更好的寫法嗎?

3 個回答

4
japhenchen
iT邦大師 1 級 ‧ 2019-07-10 07:52:45

YES

``````
Sub Main()
Dim alist(100) As Int32   '弄一個100維度的陣列
For i = 1 To 100
alist(i) = i  ' 塞預設值
Next

For Each a In alist.Where(Function(x) x Mod 2 = 0) ' 只列出除以2餘0的數字(偶數)
Console.WriteLine(a)
Next

End Sub

``````

2
paicheng0111
iT邦高手 1 級 ‧ 2019-07-09 15:22:39

NO, 用VB不行。

``````Sub test()
Dim a As Variant, myRng As Range, i As Long

Set myRng = Range(Cells(1, 1), Cells(10, 1))

myRng.FormulaR1C1 = "=row()*2"
a = Application.Transpose(myRng)

For i = LBound(a) To UBound(a)
Debug.Print (a(i))
Next i
End Sub
``````
2

iT邦大師 1 級 ‧ 2019-07-09 18:20:27

Python不熟, 不過我猜你的需求是不是這樣

``````Random rnd = new Random();
List<int> list = Enumerable.Range(1, 50).OrderBy(n => rnd.Next()).ToList();
list = list.Select(x => x * 2).ToList();
for (int i = 0; i < list.Count; i++)
Console.Write(\$"{list[i]} ");
``````
froce iT邦大師 1 級 ‧ 2019-07-09 19:08:39 檢舉