转换IEnumerable <ienumerable <t>&gt;列出<string>

时间:2018-02-25 02:38:30

标签: c# algorithm linq

我正在尝试从this answer转换代码:

{
      "Sid": "S3GetObjectPolicy",
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:GetObjectVersion"
      ],
      "Resource": [
        "*"
      ]
    },

进入字符串列表。例如,我希望此输出{1,2} {1,3}将其转换为&#34; 1,2&#34;,&#34; 1,3&#34; (这是2个单独的字符串)但我无法得到它。我甚至无法理解如何阅读上述功能的结果。这是我的代码:

# create sample data
df = pd.DataFrame({'invoice_id':[110,994528,24],
                   'customer_id':['425','a863','t311'],
                   'citems' :[{'a': 50, 'b': 46},{'a': 21, 'c': 25},{'scissor': 6, 'rock': 6}],
                  'batch':['no518','as22','af10']})

df2 = pd.DataFrame({'invoice_id':[110,994528], 'defect':['a','c']})

## merge data
df = df.merge(df2, on='invoice_id', how='left').fillna(0)

## iterate over rows and create new column
for index, row in df.iterrows():
    if row['defect'] in row['citems']:
        df.loc[index, 'defect_in_items'] = df.loc[index, 'citems'].get(df.loc[index, 'defect'],0)
    else:
        df.loc[index, 'defect_in_items'] = 0

## answer

    batch         citems               customer_id  invoice_id  defect  defect_in_items
0   no518   {'a': 50, 'b': 46}            425.          110         a       50.0
1   as22    {'a': 21, 'c': 25}            a863        994528        c       25.0
2   af10    {'scissor': 6, 'rock': 6}     t311          24          0       0.0

最后,我将所有结果添加到列表中,并包含所有可能的唯一组合 例如对于数字{1,2,3}我想要这个列表: &#39; 1&#39;&#39 2&#39;&#39 3&#39;&#39; 1,2&#39;&#39; 1,3&#39;,& #39; 2,3&#39;&#39; 1,2,3&#39;

这是我现在的代码:

static IEnumerable<IEnumerable<T>> GetKCombs<T>(IEnumerable<T> list, int length) where T : IComparable
{
    if (length == 1) return list.Select(t => new T[] { t });
    return GetKCombs(list, length - 1)
        .SelectMany(t => list.Where(o => o.CompareTo(t.Last()) > 0), 
            (t1, t2) => t1.Concat(new T[] { t2 }));
}

2 个答案:

答案 0 :(得分:2)

您可以尝试首先加入内部IEnumerables的结果

var combinations = GetKCombs(numbers, 2).Select(c => string.Join(",", c));

然后将它们连接成一个字符串

var combinationString = string.Join("; ", combinations); // "1,2; 1,3"

根据你的编辑 - 如果我找对你 - 你可以尝试

var combinationStrings = 
    numbers
        .SelectMany((_, i) =>
             GetKCombs(numbers, i + 1)              // get combinations for each 'length' 
                .Select(c => string.Join(",", c)))  // join them to a string
        .ToList();

答案 1 :(得分:1)

尝试

class Container extends Component {
    constructor(props){
        super(props);
        this.state ={
            history : []
        }
        this.handleResultChange = this.handleResultChange.bind(this)
    }
    handleResultChange(history){
        this.setState({
            history,
        })
    }

  render() {
    return (
      <div >
        <SearchBar onDataFetched={this.handleResultChange}/>
        <History data={this.state.history}/>
      </div>
    );
  }
}

它会精确打印您想要的输出。