2011-12-26 36 views
4

每個元素的第二個組件,請操作我可以用以下方式做一些操作(在這種情況下ToString)每個元素在列表中的第一個組件:在列表中的數學

{[email protected]#[[1]], [email protected]#}~Flatten~1 & /@ {{1, 2}, {3, 4, 5}} 

但是,我有幾個問題:

  • 由於顯而易見的原因,它不適用於{[email protected]#[[1]], [email protected]#}~Flatten~1 & /@ {{1, 2}, 2, {3, 4, 5}}。如何使它在 這個案例中也能工作?預期產出將爲{{"1", 2}, 2, {"3", 4, 5}}
  • 如何爲第二個(或第三個等)組件輕鬆?即我想輸出爲{{0}, {1, "2"}, {3, "4", 5}, {6, "7", 9, 10}}
  • 有沒有一種方法可以使用模式/規則(如 /.{#[[1]]->ToString[#[[1]]]})這種操作?因此,無論效率如何,請列出您可能會想到的所有解決方案。

非常感謝!

+1

相關問題:http://stackoverflow.com/questions/8580113/using-all-in-mapat-in-mathematica/。我最初認爲這是一個重複的事情,但事實並非如此,因爲它詢問了不規則和不規則的清單。 –

回答

5

我沒有意識到這與Leonid的核心功能一樣,直到我寫了它。也許這就是說,這可能比他相當複雜的功能更透明一些。

lst = {{1, 2}, 2, {3, 4, 5}}; 

Replace[lst, {a_, b__} :> {[email protected], b}, 1] 
{{"1", 2}, 2, {"3", 4, 5}}

之一,那麼可以使用{x:Repeated[_, {4}], a_, b__} :> {x, [email protected], b}, 1]第五指數等

+0

我選擇這個答案是因爲它簡單易懂。謝謝。 –

4

下面的函數應該基本上你想要做什麼:

ClearAll[applyToAll]; 
applyToAll[f_, list_List, n_Integer] := 
    applyToAll[x_ :> f[x], list, n]; 
applyToAll[rule : (_Rule | _RuleDelayed), list_List, n_Integer] := 
    Replace[ 
     list, {left : Repeated[_, {n - 1}], el_, rest___} :> 
     {left, el /. rule, rest}, {1}]; 

和可以接受的規則。例如:

In[192]:= 
applyToAll[ToString, {{1,2},2,{3,4,5}},1]//InputForm 
Out[192]//InputForm= {{"1", 2}, 2, {"3", 4, 5}} 

In[193]:= applyToAll[ToString,{{0},{1,2},{3,4,5},{6,7,9,10}},2]//InputForm 
Out[193]//InputForm= {{0}, {1, "2"}, {3, "4", 5}, {6, "7", 9, 10}} 

In[194]:= applyToAll[x_?OddQ:>ToString[x],{{0},{1,2},{3,4,5},{6,7,9,10}},2]//InputForm 
Out[194]//InputForm= {{0}, {1, 2}, {3, 4, 5}, {6, "7", 9, 10}} 
+1

+1,謝謝Leonid。 –

1

從長遠來看,我認爲這可能是一個更簡單的方法,即使它不完全是你要求的是什麼:

rep[f_, pos_][x_List] := MapAt[f, x, pos] 
rep[__][x_] := x 

lst = {{1, 2}, 2, {3, 4, 5}}; 

rep[ToString, 2] /@ lst 
{{1, "2"}, 2, {3, "4", 5}}

您可以添加任意模式條件的012定義根據需要。

+0

+1,再次感謝你。 –

2

另一種方便的方法可能是一起使用ReplacePartRuleDelayed

例如,把每個子列表的第3部分(如果存在)轉化爲字符串:

ReplacePart[#, 3 :> [email protected]#[[3]]] & /@ {{1, 2}, 
    2, {3, 4, 5}, {6, 7, 9, 10}} // InputForm 

給出作爲輸出:

{{1,2},2,{3,4, 「5」},{6,7, 「9」,10}}

同樣,把每個子列表的第1部分爲一個字符串:

ReplacePart[#, 1 :> [email protected]#[[1]]] & /@ {{1, 2}, 
    2, {3, 4, 5}} // InputForm 

給予:

{{ 「1」,2},2,{ 「3」,4,5 }}

+0

+1,謝謝TomD!很好的方式來做到這一點! –